Autofac Dependency resolution with ASP.NET MVC


The current version of ASP.NET MVC (release 3) supports a new IDependencyResolver interface that makes it easier to integrate DI frameworks.

For instance, if you are using AutoFac you can write code like this:

public class AutoFacDependencyResolver : IDependencyResolver
{
   readonly IContainer _container;
   public AutoFacDependencyResolver ( ContainerBuilder builder )
   {
      this._container = builder.Build();
   }
   public object GetService( Type serviceType )
   {
      try
      {
         return _container.Resolve( serviceType );
      }
      catch { return null; }
   }

   public IEnumerable GetServices( Type serviceType )
   {
      try
      {
         var enumerableType = typeof( IEnumerable ).MakeGenericType( serviceType );
         return _container.Resolve( enumerableType ) as IEnumerable;
      }
      catch { return null; }
   }
}

Now, it’s easy to register your types and what should resolver use:

protected void Application_Start()
{
   // register type
   var containerBuilder = new ContainerBuilder();
   containerBuilder.RegisterType<MyConcreteClass>().As<IMYInterface>();

   // set resolver
   DependencyResolver.SetResolver(
      new AutoFacDependencyResolver( containerBuilder ) );
}

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...