I have netcore webapi project and i'm using Lamar for DI. I have a service MyContextService which i register as scoped
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
[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. What am i doing wrong here?