【问题标题】:using IOC container with IdentityFactory Middleware使用 IOC 容器和 IdentityFactory 中间件
【发布时间】:2014-03-22 01:15:00
【问题描述】:

我正在尝试理解这里 per request lifetime management for usermanager 解释的 UserManagerFactory 中间件。

我创建了这个类,我从启动配置方法调用它

public class CustomUserManagerProvider
{
    public static CustomUserStore<CustomUser> CreateCustomUserStore()
    {
        return new CustomUserStore<CustomUser>(/*Need to inject dependencies here*/);
    }

    public static CustomUserManager CreateCustomUserManager(IdentityFactoryOptions<CustomUserManager> options,
        IOwinContext context)
    {
        return new CustomUserManager(context.Get<CustomUserStore<CustomUser>>());
    }
}

以及启动配置

public void Configuration(IAppBuilder app)
    {
        app.CreatePerOwinContext(CustomUserManagerProvider.CreateCustomUserStore);
        app.CreatePerOwinContext<IngramUserManager>(CustomUserManagerProvider.CreateCustomUserManager);
        ////....Other things
    }

现在,我的 CustomUserStore 有一些我想在构造函数中注入的依赖项。

IOC 容器的组合根知道如何解决这些依赖关系。

如何让CustomUserManagerProvider DI 容器感知(如果有意义的话)...

虽然这可行

public static CustomUserStore<CustomUser> CreateCustomUserStore()
    {
        var dependency = DependencyResolver.Current.GetService<ISomeDependency>();          
        return new CustomUserStore<CustomUser>(dependency);
    }

但是,我试图避免服务定位器(反)模式。这是我唯一的选择吗,这样对吗?

我正在使用 Ninject。

我不能只在组合根目录的 requestScope 中创建一个 UserManager 并注入到控制器中,那不是一回事吗?

在 Web 应用中,CreatePerOwinContext 是否与创建 InRequestScope 相同?

【问题讨论】:

    标签: c# asp.net-identity


    【解决方案1】:

    是的,如果您愿意,您可以以不同的方式将 UserManager 注入您的控制器,没有什么需要使用 CreatePerOwinContext/IdentityFactoryMiddleware。

    【讨论】:

    • Trailmax 一步一步地提供了如何将 Identity 项目模板转换为使用 Unity for DI 的模板; tech.trailmax.info/2014/09/… 他发现了一些陷阱,因此值得一读。即你不能完全删除你所有的 app.CreatePerOwinContexts for UserManager。你仍然需要一个 app.CreatePerOwinContext(() => DependencyResolver.Current.GetService());在 Startup.auth 中。
    • 使用 ILSpy,我看到的对 OwinContext.Get&lt;T&gt;() 的唯一调用是在 SecurityStampValidator 中(通过对 OwinContext.GetUserManager 的调用)。由于SecurityStampValidator 仅与CookieAuthenticationProvider 一起使用,因此如果您使用不带cookies 的WebApi,则跳过调用CreatePerOwinContext 应该是安全的。
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 2011-06-25
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多