using IOC container with IdentityFactory Middlewar

2019-03-27 07:28发布

I am trying to understand the UserManagerFactory middleware explained here per request lifetime management for usermanager.

I created this class which I am calling from the Startup Configuration method

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>>());
    }
}

And the Startup Configuration

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

Now, My CustomUserStore has some dependencies which I want to inject in the constructor.

The composition root of the IOC container knows how to resolve these dependencies.

How do I make the CustomUserManagerProvider DI container aware(If that makes sense)...

Although this works

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

But, I was trying to avoid the service locator (anti)pattern. Is this my only option, Is this even right??

I am using Ninject.

Cant I just create a UserManager in requestScope in the composition root and inject into the controllers, wont that be the same thing?

In a web app, is CreatePerOwinContext same as creating InRequestScope?

1条回答
Fickle 薄情
2楼-- · 2019-03-27 08:14

Yes, you can inject the UserManager into your controllers a different way if you like, there's nothing that requires using the CreatePerOwinContext/IdentityFactoryMiddleware.

查看更多
登录 后发表回答