0

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?

tayab
  • 130
  • 2
  • 11

1 Answers1

0

Answering my own question in hopes that this will help someone else. The problem is that TokenRequirementHandler is a singleton and MyContextService is scoped. 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.

tayab
  • 130
  • 2
  • 11