Is it possible to configure Autofac to work with ASP.NET MVC and ASP.NET Web Api

前端 未结 3 948
挽巷
挽巷 2020-12-08 02:09

Is it possible to configure Autofac to work with ASP .NET MVC and ASP .NET Web Api. I\'m aware that the dependency resolvers are different. But when using the documented app

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 02:19

    Definitely separate them. Autofac has both ASP.NET MVC and ASP.NET Web API integrations. This is not always the case but if you need the same services in both application, most probably there is something wrong with the application architecture.

    Here is how you might do this with ASP.NET Web API:

    internal class AutofacWebAPI {
    
        public static void Initialize(HttpConfiguration config) {
    
            config.DependencyResolver = new AutofacWebApiDependencyResolver(
                RegisterServices(new ContainerBuilder())
            );
        }
    
        private static IContainer RegisterServices(ContainerBuilder builder) {
    
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();
    
            //deal with your dependencies here
            builder.RegisterType().As();
            builder.RegisterType().As();
    
            return builder.Build();
        }
    }
    

    Then, register this inside the Global.asax.cs as below:

    AutofacWebAPI.Initialize(GlobalConfiguration.Configuration);
    

提交回复
热议问题