autofac 在webapi中拿到当前request的scope
https://stackoverflow.com/questions/31321386/autofac-web-api-get-current-scope
Unless you are using OWIN in your API, you should have your Autofac configuration setup in your WebAPI like this, which is the standard way to configure Autofac for WebApi.
Include nuget pacakge Autofac.Integration.WebApi
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MyType>();
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
Should you need to request the LifetimeScope like in your example, you can then request this from GlobalConfiguration.
var scope = GlobalConfiguration.Configuration.DependencyResolver.GetRequestLifetimeScope();
MyService service = scope.Resolve<MyService>();
在和Owin集成的web api中GlobalConfiguration.Configuration是无法使用的。需要使用其他方法
https://www.cnblogs.com/chucklu/p/10420034.html
https://stackoverflow.com/questions/28725753/owin-service-resolution-using-autofac
If you are in a DelegatingHandler or an ApiController you will have a reference to the current HttpRequestMessage. Use message.GetDependencyScope() to get the current request-level dependency scope to resolve services.
public HttpResponseMessage SomeControllerAction()
{
var service = this.Request.GetDependencyScope().GetService(typeof(Service));
}
protected override async void Initialize(HttpControllerContext controllerContext)
{
string requestBody = await controllerContext.Request.Content.ReadAsStringAsync();
SecurityCheckResult securityCheckResult = requestAnalyzer.SecurityCheck(requestBody);
if (securityCheckResult.Success)
{
var dependencyScope = controllerContext.Request.GetDependencyScope();
var lifetimeScope = dependencyScope.GetRequestLifetimeScope();
var parameter = new NamedParameter("OpCo", securityCheckResult.OpCo);
Program = lifetimeScope.Resolve<IProgramContract>(parameter);
Service = lifetimeScope.Resolve<IDynamicProfileService>(parameter);
} LogUtil.CreateLog(LogLevel.Message, $"BaseApiController.Initialize");
base.Initialize(controllerContext);
}
源码
using System.Web.Http.Dependencies; namespace Autofac.Integration.WebApi
{
/// <summary>
/// Extension methods to the <see cref="IDependencyResolver"/> interface.
/// </summary>
public static class DependencyResolverExtensions
{
/// <summary>
/// Gets the root lifetime scope from the Autofac dependency resolver.
/// </summary>
/// <param name="dependencyResolver">
/// The dependency resolver from which the root lifetime scope should be retrieved.
/// </param>
public static ILifetimeScope GetRootLifetimeScope(this IDependencyResolver dependencyResolver)
{
var resolver = dependencyResolver as AutofacWebApiDependencyResolver;
return (resolver == null) ? null : resolver.Container;
} /// <summary>
/// Gets the request lifetime scope from the Autofac dependency scope.
/// </summary>
/// <param name="dependencyScope">
/// The dependency scope from which the request lifetime scope should be retrieved.
/// </param>
public static ILifetimeScope GetRequestLifetimeScope(this IDependencyScope dependencyScope)
{
var scope = dependencyScope as AutofacWebApiDependencyScope;
return (scope == null) ? null : scope.LifetimeScope;
}
}
}
而Microsoft.AspNet.WebApi.Core.5.2.7中,有一个扩展HttpRequestMessage的静态类public static class HttpRequestMessageExtensions
public static IDependencyScope GetDependencyScope(this HttpRequestMessage request);
所以我们可以通过request去拿到IDependencyScope 。
然后autofac扩展了IDependencyScope ,增加了1个GetRequestLifetimeScope的方法,拿到这个scope就可以进行resolve了。
autofac 在webapi中拿到当前request的scope的更多相关文章
- Autofac - MVC/WebApi中的应用
Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...
- webapi 中使用 protobuf
相比json来说,好处是速度更快,带宽占用更小.其效果大致等于json+Gzip. 在webapi中使用protobuf的方法为: 引用nuget包 Install-Package protobuf- ...
- 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)
一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...
- 在WebAPI中自动创建Controller
在MIS系统中,大部分的操作都是基本的CRUD,并且这样的Controller非常多. 为了复用代码,我们常常写一个泛型的基类. public class EntityController<T& ...
- webApi中参数传递
webApi中参数传递 一:无参数的get方法: 前端: function GetNoParam() { //为了统一:我们都采用$.ajax({}) 方法; $.ajax({ url: '/a ...
- 在MVC或WEBAPI中记录每个Action的执行时间和记录下层方法调用时间
刚才在博客园看了篇文章,http://www.cnblogs.com/cmt/p/csharp_regex_timeout.html 突然联想到以前遇到的问题,w3wp进程吃光CPU都挂起IIS进程 ...
- Asp.Net WebAPI 中Cookie 获取操作方式
1. /// <summary> /// 获取上下文中的cookie /// </summary> /// <returns></returns> [H ...
- 关于ASP.NET WebAPI中HTTP模型的相关思考
对于.NET的分布式应用开发,可以供我们选择的技术和框架比较多,例如webservice,.net remoting,MSMQ,WCF等等技术.对于这些技术很多人都不会陌生,即时没有深入的了解,但是肯 ...
- AutoFac+MVC+WebApi源码----我踩过的坑
发现网上关于AutoFac的Demo源码比较少,综合MVC和WepApi的更少.所以贴出源码 WebApi项目(MVC4不需要引用,历史遗留问题,人懒没删) 建项目 新建类库IAutoFacDal(接 ...
随机推荐
- Lucene中的域选项
Field类是lucene在索引过程中的一个很重要的类,该类控制着域值被索引的方式 域选项主要包括以下几种选项:域索引选项.域存储选项.域的项向量选项.域的排序选项等 域索引选项:通过倒排索引来控制域 ...
- 什么是runtime?什么是webgl?
一 什么是Runtime? Egret官方解释:https://www.egret.com/products/runtime.html 二.什么是WebGL渲染? egret官方解释:http://d ...
- 【BZOJ1801】[Ahoi2009]chess 中国象棋 DP
[BZOJ1801][Ahoi2009]chess 中国象棋 Description 在N行M列的棋盘上,放若干个炮可以是0个,使得没有任何一个炮可以攻击另一个炮. 请问有多少种放置方法,中国像棋中炮 ...
- linux shell中FS、OFS、RS、ORS图解
在linux 中,总是会忘记FS\OFS\RS\ORS的使用 下面一张图非常明晰的显示
- android异常:Can not perform this action after onSaveInstanc
extends:http://zhiweiofli.iteye.com/blog/1539467 本人某个android项目开发阶段一直运行良好,直到上线前夕,在某款跑着android 4.03系统的 ...
- 微信小程序 --- app.json文件
app.json文件用于配置项目:用于对小程序进行全局设置: pages:定义小程序的路由.(凡是不在这个配置里面的东西,都无法打开) (特别注意:结尾不能有 逗号 否则会出错) window:定义小 ...
- ajax解决跨域方法(适用于自己写接口解决跨域)
原因是这样的:最近用PHP开发了一个网站,这个网站需要提供接口,接口开发完成之后,在本地进行请求,跨域测试. jsonp处理跨域和用PHP函数来处理跨域就不说了. 现在说的使用用 header 这个来 ...
- Java 泛型 <? super T> 中 super 怎么 理解?与 < ? extends T>有何不同?
Java 泛型 <? super T> 中 super 怎么 理解?与 extends 有何不同? 简介 前两篇文章介绍了泛型的基本用法.类型擦除以及泛型数组.在泛型的使用中,还有个重要的 ...
- reflect 机制
1: Class.forName的作用?为什么要用? 答:调用该访问返回一个以字符串指定类名的类的对象. 2: 通过反射,有几种方法可以实例化Class类对象? 3种,第一种:Class.forNam ...
- 容斥原理解决某个区间[1,n]闭区间与m互质数数量问题
首先贴出代码(闭区间[1,n]范围内和m互质的数) 代码: int solve(II n,II m){ vector<II>p; ;i*i<=m;i++){ ){ p.push_ba ...