使用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();
        }

 

posted @ 2014-10-28 18:11  学亮  阅读(2113)  评论(0编辑  收藏  举报