[英]Lamar AddScoped not working as expected net core webapi
I have netcore webapi project and i'm using Lamar for DI.我有 netcore webapi 项目,我正在使用 Lamar 进行 DI。 I have a service MyContextService which i register as scoped
我有一个服务 MyContextService 我注册为范围
public class LifetimeRegistry : ServiceRegistry
{
public LifetimeRegistry()
{
this.AddScoped<MyContextService>();
}
}
I use this service in 2 places, firstly in a authorization handler (where i also set the context).我在两个地方使用此服务,首先是在授权处理程序中(我还设置了上下文)。
public class TokenRequirement : IAuthorizationRequirement { }
public class TokenRequirementHandler : AuthorizationHandler<TokenRequirement>, IAuthorizationRequirement
{
private readonly MyContextService _cxtService;
public TokenRequirementHandler(MyContextService cxtService)
{
_cxtService = _cxtService;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TokenRequirement requirement)
{
// other code..
_cxtService.InitContext(); // This sets some context that's valid for this http request
}
}
And the second place is in a controller第二名是controller
[Authorize(Policy = "TokenRequired")]
public class MyController
{
private readonly MyContextService _cxtService;
public MyController(MyContextService cxtService)
{
_cxtService = _cxtService;
// The context is null & service has a different hashcode
var cxt = _cxtService.GetContext();
}
}
In this controller, i expect the context to be set but it isn't and i noticed that the 2 instances have different hashcodes.在这个 controller 中,我希望设置上下文,但事实并非如此,我注意到这两个实例具有不同的哈希码。 What am i doing wrong here?
我在这里做错了什么?
Answering my own question in hopes that this will help someone else.回答我自己的问题,希望这对其他人有帮助。 The problem is that
TokenRequirementHandler
is a singleton and MyContextService
is scoped.问题是
TokenRequirementHandler
是 singleton 并且MyContextService
是作用域。 This makes a lot of sense when you think about it but it wasn't so obvious at the time.当您考虑它时,这很有意义,但当时并不那么明显。
My solution was to make TokenRequirementHandler
scoped.我的解决方案是使
TokenRequirementHandler
范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.