maandag 4 maart 2013

Don't register dependencies in global.asax


When you use a Inversion of Control container to wsire up the dependencies, don't register the dependencies in the global.asax of your web project.

Something like this is what you will find in the Getting Started of most IoC containers;


public class MvcApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      ...

      var builder = new Autofac.ContainerBuilder();

      builder.RegisterControllers(typeof(MvcApplication).Assembly)
         .PropertiesAutowired();

      builder.RegisterType<SomeType>();
      builder.RegisterType<SomeotherType>();
      builder.RegisterType<AnotherType>();

      var container = builder.Build();

      DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
   }
}


The problem lies with the marked lines. When you add a WCF project you probably will use the same registrations. And then you add a Windows Service project, and you have to copy this code again. And soon you have three or even more places with the same duplicated code. As you application gets bigger, the number of registrations will  grow, and everytime you have to update the registrations at three or more places.


Solution

The solution is to use Modules:

Create a new project in your Visual Studio solution and add a class like this:


public class SomeDependenciesModule : Autofac.Module
{
   protected override void Load(ContainerBuilder builder)
   {
      builder.RegisterType<SomeType>();
      builder.RegisterType<SomeotherType>();
      builder.RegisterType<AnotherType>();
   }
}


(You can split the registrations in seperate modules if you like)

Now you can register the module like this:


public class MvcApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      ...

      var builder = new Autofac.ContainerBuilder();

      builder.RegisterControllers(typeof(MvcApplication).Assembly)
         .PropertiesAutowired();

      builder.RegisterModule(new SomeDependenciesModule());

      var container = builder.Build();

      DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
   }
}


Your WCF project and Windows Service will also only register the module. When you add a new dependency to the SomeDependenciesModule, you will only have to add it once, and not three or more times.



Geen opmerkingen:

Een reactie posten