码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-10-28 19:59:44      阅读:271      评论:0      收藏:0      [点我收藏+]

标签: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上实现依赖注入

标签:cWeb   style   blog   http   io   color   ar   使用   sp   

原文地址:http://www.cnblogs.com/yxlblogs/p/4057485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!