【问题标题】:Resolve Autofac service within InstancePerLifetimeScope on Owin Startup在 Owin 启动时解析 InstancePerLifetimeScope 中的 Autofac 服务
【发布时间】:2015-04-14 00:00:17
【问题描述】:

我无法找到通过 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),
             });         
          }

有人有建议吗?

【问题讨论】:

    标签: c# inversion-of-control autofac owin startup


    【解决方案1】:

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

    这个类没有被设计为注入。如果你想解决一个请求的依赖关系,你必须使用每个方法提供的 owinContext 手动解决它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多