SimpleInjector不起作用--OWIN上的Web API

问题描述 投票:0回答:1

OwinStartup.cs

public class OwinStartup
{
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void Configuration(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
        var config = new HttpConfiguration();

        SimpleInjectorConfig.Configure(app);
        ConfigureOAuth(app);
        WebApiConfig.Register(config);
        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config);  
    }

    private static void ConfigureOAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(
            () => (IDisposable)GlobalConfiguration.Configuration.DependencyResolver.GetService(
                typeof(AppUserManager)));

        var options = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new AppAuthProvider(),
            AllowInsecureHttp = true,
        };

        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

SimpleInjectorConfig.cs

public static class SimpleInjectorConfig
{
    public static void Configure(IAppBuilder app)
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

        //allows scoped instances to be resolved during OWIN request
        app.Use(async (context, next) =>
        {
            using (AsyncScopedLifestyle.BeginScope(container))
            {
                await next();
            }
        });

        container.Register<AppIdentityDbContext>(Lifestyle.Scoped);
        container.Register<AppUserManager>(Lifestyle.Scoped);
        container.Register(
            () =>
                container.IsVerifying
                    ? new OwinContext().Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);
        container.Register<AppSignInManager>(Lifestyle.Scoped);

        container.Verify();

        GlobalConfiguration.Configuration.DependencyResolver =
            new SimpleInjectorWebApiDependencyResolver(container);
    }
}

所以在我的qazxsw poi的实现中称为qazxsw poi我试图使用以下代码获取OAuthAuthorizationServerProvider的实例(我需要找到用户):

AppAuthProvider

但不知道为什么我仍然得到AppUserManager。我真的不知道该怎么做,因为每个事情似乎都配置正确。有任何想法吗 ?谢谢 !

c# asp.net-web-api owin asp.net-identity-2 simple-injector
1个回答
0
投票

我找到了解决方案。更新的代码如下:

OwinStartup.cs

var manager = context.OwinContext.Get<AppUserManager>();

SimpleInjectorConfig.cs

null

也许有人会用它。

© www.soinside.com 2019 - 2024. All rights reserved.