Sunday, January 30, 2011

IoC / Dependency Injection

back

The basic idea behind Inversion of Control in context is dependency injection; you want to remove dependencies from your application and that dictates need of a tool to plug in these dependencies.
Other terms you might have heard floating around in this context is Contructor, Setter and Interface Injection; which is way of programming where and how dependecies are injected.
In example below; your car listing service depends on car repository whcih connects to db and gets you data.

public class CarLister
{
      ICarRepository _repository;
      public CarLister(ICarRepository repository){
            _repository = repository;
      }
}

There are numerous dependency injection frameworks available; I have used structure map and find is sufficient for needs of application. Idea is to scan assemblies and generate plug in graph for all objects; this allows structure map to contruct objects on demand.

Below is how to configure structure map; configuration below would allow you to scan all assemblies and register all declared registries.

 public class Bootstrapper
    {
        public static void Bootstrap()
        {
            //Initialize StructureMap
            ObjectFactory.Initialize(r =>
                r.Scan(assembly =>
                {
                    ScanProjectAssemblies(assembly);
                    if (assembly == null)
                        return;
                  
                    assembly.AddAllTypesOf(typeof (IStartupTask));                                                            

                    assembly.LookForRegistries();              
                  }));
          
        }

       /// <summary>
       /// Helper method to determine the project's assemblies to scan
       /// </summary>
       internal static void ScanProjectAssemblies(IAssemblyScanner assembly)
       {
           assembly.TheCallingAssembly();
           assembly.AssembliesFromApplicationBaseDirectory();
       }
    }

You can declare registries as per your need:


public class DomianRegistry: Registry
{
                  public DomianRegistry()
                  {
                              For(typeof(IRepository<>)).Use(typeof(Repository<>));
                  }

No comments:

Post a Comment