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

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了。

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(1221)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示