Sunday, January 30, 2011

IoC / Dependency Injection


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 =>
                    if (assembly == null)
                    assembly.AddAllTypesOf(typeof (IStartupTask));                                                            


       /// <summary>
       /// Helper method to determine the project's assemblies to scan
       /// </summary>
       internal static void ScanProjectAssemblies(IAssemblyScanner assembly)

You can declare registries as per your need:

public class DomianRegistry: Registry
                  public DomianRegistry()

No comments:

Post a Comment