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(接 ...
随机推荐
- 超级小的web手势库AlloyFinger
针对多点触控设备编程的Web手势组件,快速帮助你的web程序增加手势支持,也不用再担心click 300ms的延迟了.拥有两个版本,无依赖的独立版和react版本.除了Dom对象,也可监听Canvas ...
- 解决在微信中部分IOS不能自动播放背景音乐
前言在做各种HTML5场景页面的时候,插入背景音乐是一个很普遍的需求.我们都知道,IOS下的safari是无法自动播放音乐的,以至一直以来造成一种错误的认识,iso是无法自动播放媒体资源的.直到微信火 ...
- node中的对象
1. class的概念 定义一个class,属性都是private,方法都是public. Hello.js: 使用class index.js: 2. 单例类 使用exports而不是module. ...
- Unity3D笔记十一 定制导航菜单栏
一.定制导航栏 Unity导航菜单栏位于游戏引擎界面的顶部,其中有很多选项且含义各不相同.Unity为开发者提供了导航菜单栏的程序接口,使用代码可以动态添加菜单栏中的选项以及子项 using Unit ...
- 310实验室OTL问题(2)
1.PyOptimization代码学习心得 (1).该部分由三个分块组成(按完成的相应的任务).第一部分,运行函数. 以optimization.py为入口程序,其思路是:首先获取路径,然后,初始化 ...
- 170807、intellij idea maven集成lombok实例
简介: lombok 通过简单注解方式简化java代码.(如消除实体对象的get/setter方法.日志对象声明等...) 安装步骤: 1.选择支持注解处理:Settings-->Build-- ...
- SpringCloud--Ribbon负载均衡
Ribbon实现客户端负载均衡 负载均衡:是对系统的高可用.网络压力的缓解和处理能力扩容的重要手段之一. 硬件负载均衡:主要通过在服务器节点之间安装专门用于负载均衡的设备: 软件负载均衡:通过在服务器 ...
- poj1821 Fence【队列优化线性DP】
Fence Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 6122 Accepted: 1972 Description ...
- codeforces#516 Div2---ABCD
A---Make a triangle! http://codeforces.com/contest/1064/problem/A 题意: 给定三个整数表示三角形的边.每次给边长可以加一,问至少要加多 ...
- html lang="zh-cn"解决Mac版Firefox中文字体显示问题
这两天在Mac下被Firefox的中文字体显示问题所困扰.在Firefox中将Sans-serif字体设置为SimSun-ExtB(新宋体)或英文字体(这时会用Mac默认中文字体),如下图: 浏览园子 ...