使用Autofac在ASP.NET Web API上實現依賴注入

在ASP.NET Web API裏使用Autofacui

1.經過NuGet安裝Autofac.WebApi(當時安裝的是Autofac 3.1.0)spa

PM > Install-Package Autofac.WebApicode

2.在App_Start文件夾下新建AutofacWebApiConfig類blog

 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中添加如下代碼io

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();
        }
相關文章
相關標籤/搜索