简体   繁体   中英

Lamar AddScoped not working as expected net core webapi

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM