在 Owin 启动时解决 Autofac 在 InstancePerLifetimeScope 内的服务问题。

3

我无法找到一种正确的方法来通过Autofac解决在构建Owin上下文时使用且在请求结束时被处理的服务。

由于此时OwinContext仍在构建中,因此无法通过调用HttpContext.Current.GetOwinContext().GetAutofacLifetimeScope()找到LifetimeScope。此时还不可用OwinContext。

在我的代码中,IAdfsAuthorizationProvider服务直接在Container中解析,但在请求后没有被处理并且长时间存活。

我可以通过调用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),
             });         
          }

有没有人有建议?
1个回答

11

OAuthAuthorizationServerProvider 是一个单例,它为所有请求调用方法。

此类并未设计为可注入。如果您想解析一个请求的依赖关系,您必须使用每个方法提供的 owinContext 手动解析它。

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

        return base.GrantAuthorizationCode(context);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接