错误:请求的服务“ Microsoft.Owin.IOwinContext”尚未注册

时间:2019-07-22 09:20:41

标签: asp.net-mvc owin autofac

我正在为租户通过owin启动获取连接字符串。我有MultiTenantOwinMiddleware来处理Tenant.Startup类中有以下代码。 我是Owin的初学者。

builder.RegisterType<OwnerDbContext>()
            .AsSelf()
            .WithParameter(new ResolvedParameter(
                (pi, ctx) => pi.ParameterType == typeof (string) && pi.Name == "ConnectionString",
                (pi, ctx) => GetTenantConnectionString(ctx)))
            .InstancePerRequest();

private static string GetTenantConnectionString(IComponentContext ctx)
    {
        var owinContext = ctx.Resolve<IOwinContext>();
        var tenant = owinContext.GetCurrentTenant<OwnerTenant>();
        return tenant != null ? tenant.ConnectionString : "XYZ";
    }

我收到此错误。 所请求的服务“ Microsoft.Owin.IOwinContext”尚未注册。为避免此异常,请注册一个组件以提供服务,或者使用IsRegistered()检查服务注册,或者使用ResolveOptional()方法解决可选的依赖项。

修改

public static void ConfigureIoCContainer(此IAppBuilder应用程序HttpConfiguration配置)         {

        var container = RegisterInstances(); // Function for component registration

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        app.UseAutofacMiddleware(container);



        app.Use(async (ctx, next) =>
        {
            using (var scope = container.BeginLifetimeScope(b => b.RegisterInstance(ctx).As<IOwinContext>()))
            {
                ctx.Set<ILifetimeScope>("idsrv:AutofacScope", scope);
                await next();
            }
        });

    }

任何帮助将不胜感激。 非常感谢

0 个答案:

没有答案