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

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
G
Google Developers Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Check Point Blog
J
Java Code Geeks
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
量子位
A
About on SuperTechFans
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - 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>();