• 使用Autofac在ASP.NET Web API上实现依赖注入


    在ASP.NET Web API里使用Autofac

    1.通过NuGet安装Autofac.WebApi(当时安装的是Autofac 3.1.0)

    PM > Install-Package Autofac.WebApi

    2.在App_Start文件夹下新建AutofacWebApiConfig类

     public class AutofacWebApiConfig
        {
            public static void Run()
            {
                SetAutofacWebApi();
            }
    
            private static void SetAutofacWebApi()
            {
                ContainerBuilder builder = new ContainerBuilder();
                HttpConfiguration config = GlobalConfiguration.Configuration;
                // Register API controllers using assembly scanning.
                builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
                builder.RegisterType<ValueService>().As<IValueService>()
                    .InstancePerApiRequest();
                var container = builder.Build();
                // Set the WebApi dependency resolver.
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            }

    3.在Global中添加以下代码

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                //Call Autofac DI configurations   
                AutofacWebApiConfig.Run();
            }
  • 相关阅读:
    有向无环图
    2016
    Permutation Descent Counts(递推)
    Rikka with Subset
    hihoCoder 1549 或运算和
    Young Maids
    1925: [Sdoi2010]地精部落
    Problem H. Hotel in Ves Lagos
    改变presentModalView大小
    no such file to load -- bundler/setup
  • 原文地址:https://www.cnblogs.com/yxlblogs/p/4057485.html
Copyright © 2020-2023  润新知