Autofac and ASP.NET Web API ApiController

前端 未结 2 921
悲&欢浪女
悲&欢浪女 2021-02-08 15:57

I have been using autofac with MVC 3 for a while and love it. I recently upgraded a project to MVC 4 and everything seems to be working except for Web Api ApiControllers. I am g

2条回答
  •  轮回少年
    2021-02-08 16:40

    I just configured this on one of my apps. There are different ways of doing it but I like this approach:

    Autofac and ASP.NET Web API System.Web.Http.Services.IDependencyResolver Integration

    First I created a class which implements 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 GetServices(Type serviceType) {
    
            Type enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
            object instance = _container.Resolve(enumerableServiceType);
            return ((IEnumerable)instance).Cast();
        }
    }
    
    
    

    And I have another class which holds 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().As();
            builder.RegisterType().As();
    
            return
                builder.Build();
        }
    }
    

    Then, initialize it at Application_Start:

    protected void Application_Start() {
    
        //...
    
        AutofacWebAPI.Initialize();
    
        //...
    }
    

    I hope this helps.

    提交回复
    热议问题