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了。
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了