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

前端 未结 3 951
挽巷
挽巷 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条回答
  •  Happy的楠姐
    2020-12-08 02:40

    I thought I'd add a little help those struggling with this in mvc5 and web api 2.

    First add nuget packages

    • Autofac
    • Autofac asp.net mvc 5 integration
    • Autofac asp.net web api 2.x integration

    in global add in application_start (or as app_start class) add call to the below class

    AutofacConfig.RegisterAutoFac();
    

    now add this class under App_start

    using System.Reflection;
    using System.Web.Http;
    using System.Web.Http.Controllers;
    using System.Web.Mvc;
    using Autofac;
    using Autofac.Integration.Mvc;
    using Autofac.Integration.WebApi;
    
    namespace Example1.Web
    {
        public class AutofacConfig
        {
            public static IContainer RegisterAutoFac()
            {
                var builder = new ContainerBuilder();
    
                AddMvcRegistrations(builder);
                AddRegisterations(builder);
    
                var container = builder.Build();
    
                DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
                GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    
                return container;
            }
    
            private static void AddMvcRegistrations(ContainerBuilder builder)
            {
                //mvc
                builder.RegisterControllers(Assembly.GetExecutingAssembly());
                builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
                builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
                builder.RegisterModelBinderProvider();
    
                //web api
                builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).PropertiesAutowired();
                builder.RegisterModule();
            }
    
            private static void AddRegisterations(ContainerBuilder builder)
            {
                //builder.RegisterModule(new MyCustomerWebAutoFacModule());
            }
        }
    }
    

    From now for each new assembly you add to the project add a new module and then register the module in the AddRegisterations function (example given)

    Note:

    I returned the container, this isn't necessary.

    This scans the current assembly for modules so don't add local modules in AddRegisterations otherwise you will register everything twice.

提交回复
热议问题