惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
D
Docker
有赞技术团队
有赞技术团队
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
爱范儿
爱范儿
H
Help Net Security
美团技术团队
MyScale Blog
MyScale Blog
B
Blog RSS Feed
C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
阮一峰的网络日志
阮一峰的网络日志
A
About on SuperTechFans
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
G
Google Developers Blog
月光博客
月光博客
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Blog — PlanetScale
Blog — PlanetScale
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs

博客园 - rosanshao

使用sc 命令写脚本 添加和删除服务 简单应用 Win 10激活 couchbase map reduce StartWith 测试 笔记,转 Couchbase II( View And Index) Couchbase I SqlIO优化 死锁检测 MemCached 安装笔记 Asp.Net异步编程-使用了异步,性能就提升了吗? Sql Server 2005/2008 SqlCacheDependency查询通知的使用总结 WCF .NET REST调用方式 WCF HelpPage 和自动根据头返回JSON XML .net 4.0 新特性 Linq 并行化处理 IIS 假死状态处理 gmap jQuery插件开发 StatusCode - rosanshao - 博客园
Autofac Mvc Webapi注入笔记
rosanshao · 2013-02-02 · via 博客园 - rosanshao

Autofac Mvc Webapi注入笔记

 private static void MvcIoc(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => !t.IsAbstract && (typeof(IHttpController).IsAssignableFrom(t) || typeof(IController).IsAssignableFrom(t))).InstancePerLifetimeScope();
            var container = builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);//ApiController WebApi注入 
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//普通的MVC Controller 注入 
            
        }


MVC Filter注入 通过属性注入

builder.RegisterFilterProvider();

在Filter里通过属性就可以了

在Web Api请求中,没有注入,又需要获取其实例,可以这样获取

IDependencyScope dependencyScope = this.Request.GetDependencyScope();
ILifetimeScope requestLifetimeScope = dependencyScope.GetRequestLifetimeScope();
var customerService = requestLifetimeScope.Resolve<ICustomerService>();

在MVC中这样获取

var customerService = System.Web.Mvc.DependencyResolver.Current.GetService(typeof (ICustomerService));

或者
var customerService = System.Web.Mvc.DependencyResolver.Current.GetService<ICustomerService>();