標籤:cWeb style blog http io color ar 使用 sp
在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(); }
使用Autofac在ASP.NET Web API上實現依賴注入