簡體   English   中英

Lamar AddScoped 未按預期工作網絡核心 webapi

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM