I just configured this in one of my applications. There are different ways to do this, but I like this approach:
Autofac and ASP.NET Web API System.Web.Http.Services.ID Dependencies Resolver Integration
First, I created a class that implements the System.Web.Http.Services.IDependencyResolver interface.
internal class AutofacWebAPIDependencyResolver : System.Web.Http.Services.IDependencyResolver { private readonly IContainer _container; public AutofacWebAPIDependencyResolver(IContainer container) { _container = container; } public object GetService(Type serviceType) { return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null; } public IEnumerable<object> GetServices(Type serviceType) { Type enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType); object instance = _container.Resolve(enumerableServiceType); return ((IEnumerable)instance).Cast<object>(); } }
And I have another class that contains my registrations:
internal class AutofacWebAPI { public static void Initialize() { var builder = new ContainerBuilder(); GlobalConfiguration.Configuration.ServiceResolver.SetResolver( new AutofacWebAPIDependencyResolver(RegisterServices(builder)) ); } private static IContainer RegisterServices(ContainerBuilder builder) { builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired(); builder.RegisterType<WordRepository>().As<IWordRepository>(); builder.RegisterType<MeaningRepository>().As<IMeaningRepository>(); return builder.Build(); } }
Then initialize it in Application_Start :
protected void Application_Start() {
Hope this helps.
tugberk Feb 27 '12 at 8:38 2012-02-27 08:38
source share