![](/img/trans.png)
[英]StructureMap -> Lamar .NET Core 3.1 service creation not working
[英]Lamar AddScoped not working as expected net core webapi
我有 netcore webapi 项目,我正在使用 Lamar 进行 DI。 我有一个服务 MyContextService 我注册为范围
public class LifetimeRegistry : ServiceRegistry
{
public LifetimeRegistry()
{
this.AddScoped<MyContextService>();
}
}
我在两个地方使用此服务,首先是在授权处理程序中(我还设置了上下文)。
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
}
}
第二名是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();
}
}
在这个 controller 中,我希望设置上下文,但事实并非如此,我注意到这两个实例具有不同的哈希码。 我在这里做错了什么?
回答我自己的问题,希望这对其他人有帮助。 问题是TokenRequirementHandler
是 singleton 并且MyContextService
是作用域。 当您考虑它时,这很有意义,但当时并不那么明显。
我的解决方案是使TokenRequirementHandler
范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.