簡體   English   中英

在Owin Startup上解析InstancePerLifetimeScope中的Autofac服務

[英]Resolve Autofac service within InstancePerLifetimeScope on Owin Startup

我無法找到通過Autofac解析服務的正確方法,該方法在構造 Owin上下文時使用並且也在請求端處理

由於此時OwinContext仍在構建中,因此無法通過調用HttpContext.Current.GetOwinContext().GetAutofacLifetimeScope()找到LifetimeScope。 OwinContext還沒有。

在我的代碼中, IAdfsAuthorizationProvider服務直接在Container處解析,但在請求之后不會被處理並且IAdfsAuthorizationProvider時間更長。

我可以通過調用container.BeginLifetimeScope()來創建一個新的LifeTimeScope,但現在LifeTime被分離了請求,並且可能會解析同一請求中的不同實例。 並且無法在正確的時間自行處理lifeTimeScope。

    public void Configure(IAppBuilder app)
    {
         var builder = new ContainerBuilder();    
         builder.RegisterType<AdfsAuthorizationProvider>().As<IAdfsAuthorizationProvider>().InstancePerLifetimeScope();

         var container = builder.Build();

         app.UseAutofacMiddleware(container);

         // **Service that's not binding to the request lifetime.**
         var service = container.Resolve<IAdfsAuthorizationProvider>();

         app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
             {
                Provider = new AuthorizationServerProvider(service),
             });         
          }

有沒有人有建議?

OAuthAuthorizationServerProvider是一個為所有請求調用方法的單例

此類尚未設計為注入。 如果要解析一個請求的依賴關系,則必須使用每個方法提供的owinContext手動解析它

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task GrantAuthorizationCode(
        OAuthGrantAuthorizationCodeContext context)
    {
        IAdfsAuthorizationProvider authorizationProvider =
            context.OwinContext
                   .GetAutofacLifetimeScope()
                   .Resolve<IAdfsAuthorizationProvider>();

        return base.GrantAuthorizationCode(context);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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