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>();

Autofac WebApi configuration reference

在和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);
}

源码

https://github.com/autofac/Autofac.WebApi/blob/develop/src/Autofac.Integration.WebApi/DependencyResolverExtensions.cs

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的更多相关文章

  1. Autofac - MVC/WebApi中的应用

    Autofac前面写了那么多篇, 其实就是为了今天这一篇, Autofac在MVC和WebApi中的应用. 一.目录结构 先看一下我的目录结构吧, 搭了个非常简单的架构, IOC(web), IBLL ...

  2. webapi 中使用 protobuf

    相比json来说,好处是速度更快,带宽占用更小.其效果大致等于json+Gzip. 在webapi中使用protobuf的方法为: 引用nuget包 Install-Package protobuf- ...

  3. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  4. 在WebAPI中自动创建Controller

    在MIS系统中,大部分的操作都是基本的CRUD,并且这样的Controller非常多. 为了复用代码,我们常常写一个泛型的基类. public class EntityController<T& ...

  5. webApi中参数传递

    webApi中参数传递 一:无参数的get方法: 前端:    function GetNoParam() { //为了统一:我们都采用$.ajax({}) 方法; $.ajax({ url: '/a ...

  6. 在MVC或WEBAPI中记录每个Action的执行时间和记录下层方法调用时间

    刚才在博客园看了篇文章,http://www.cnblogs.com/cmt/p/csharp_regex_timeout.html  突然联想到以前遇到的问题,w3wp进程吃光CPU都挂起IIS进程 ...

  7. Asp.Net WebAPI 中Cookie 获取操作方式

    1. /// <summary> /// 获取上下文中的cookie /// </summary> /// <returns></returns> [H ...

  8. 关于ASP.NET WebAPI中HTTP模型的相关思考

    对于.NET的分布式应用开发,可以供我们选择的技术和框架比较多,例如webservice,.net remoting,MSMQ,WCF等等技术.对于这些技术很多人都不会陌生,即时没有深入的了解,但是肯 ...

  9. AutoFac+MVC+WebApi源码----我踩过的坑

    发现网上关于AutoFac的Demo源码比较少,综合MVC和WepApi的更少.所以贴出源码 WebApi项目(MVC4不需要引用,历史遗留问题,人懒没删) 建项目 新建类库IAutoFacDal(接 ...

随机推荐

  1. 对规范中每个模块只允许一个id的理解

    优点: 每个模块只有一个ID,并且在css中不适用ID,ID从模板中传入js中,则该模块的复用灵活性会非常高.想要复用该模块时,只需要改动两个地方.一个是html中的ID,另外一个是写到全局conf. ...

  2. IT公司常见的内网漏洞表格

    访问控制类漏洞与隐患 这一类漏洞与隐患属于访问控制与身份鉴别问题,一般有没有配置访问控制.访问控制弱(弱口令或者空口令),身份鉴别可以绕过等问题 漏洞协议组件 漏洞类型 漏洞评级 SSH 弱口令 严重 ...

  3. (转)梯度下降法及其Python实现

    梯度下降法(gradient descent),又名最速下降法(steepest descent)是求解无约束最优化问题最常用的方法,它是一种迭代方法,每一步主要的操作是求解目标函数的梯度向量,将当前 ...

  4. .NET中将中文符号转换成英文符号

    public static string ConvertToEn(string text) { const string s1 = ".:,?!.“”‘’"; const stri ...

  5. IIS中User-mode caching引起的Cache-Control不为public的问题

    在IIS的Output caching中如果启用了User-mode caching将引起Cache-Control为no-cache,从而造成页面不能被浏览器或代理服务器缓存. web.config ...

  6. CRM - 起步

    一.crm简介 crm 客户关系管理软件 ( Customer Relationship Management ) 二.起步 models.py 表结构 from django.db import m ...

  7. Hotel---poj3667(线段树区间问题)

    题目链接:http://poj.org/problem?id=3667 题意:酒店有n个房间,现有m个团队,每个团队需要连续 d 个房间,现在有两个操作,1:需要 d 个房间,2:从 x 开始连续 d ...

  8. 用 mongodb 储存多态消息/提醒类数据(转)

    原文:http://codecampo.com/topics/66 前天看到 javaeye 计划采用mongoDB实现网站全站消息系统,很有同感,mongodb 很适合储存消息类数据.之前讨论了如何 ...

  9. Windows中杀死某个端口的进程

    最近写项目,总是出现端口被占用的问题,原来傻傻的把电脑重启一下,终于有一天受不了了,想要想办法解决.刚开始从网上找了好多教程,发现不行.开始自己尝试,终于,成功的将占用端口的进程杀掉.在此记录下过程( ...

  10. shell export 命令

    export 命令作用是 把变量导出 也可以用export来定义环境变量 导入 定义的变量 这样的话类似于python面向对象的self.变量 一样 在脚本到处调用这个变量