Reputation: 314
I have an ASP.NET Web API project using ASP.NET Identity for authentication/authorization. I've inserted my own custom Identity implementation, namely my own UserStore to talk with Azure Tables, and removed the EF/SQL Server stuff. However, most of the docs I see out there recommend creating an instance of the UserManagerFactory within the Startup.Auth.cs class as follows:
public static Func<UserManager<CustomIdentityModel>> UserManagerFactory { get; set; }
UserManagerFactory = () => new UserManager<CustomIdentityModel>(new CustomUserStore<CustomIdentityModel>());
My CustomUserStore has a dependency on a repository in another project, which I dependency inject into the constructor.
private readonly IRepository _repo;
public CustomUserStore(IRepository repo)
{
_repo = repo;
}
However, creating a "new CustomUserStore()" in the Startup.Auth.cs is an anti-pattern and cannot resolve the dependency. What is the right way to resolve this dependency when creating a UserManager? I'd like to either not have to "new up" a UserManagerFactory, or somehow resolve the dependency inline:
new UserManager<CustomUserModel>(container.Resolve<IRepository>());
Then the question becomes, how to get the single IOC container instance...
Upvotes: 1
Views: 1007
Reputation: 1248
Create an static field in your global.asax or owin startup class to hold a reference for ioc container, in your container bootstrap setup set the static field value.
after that you can access the ioc container from somewhere, in your Startup.Auth.cs class you can read the ioc static field container and initialize inline UserStore.
Owin Class:
public class Startup {
public static IUnityContainer Container; //Static field for hold ioc container reference.
public void Configuration(IAppBuilder app)
{
//Code Omitted for brevity
Container = YourIoCContainerReference:
}
}
}
So you can do an inline initialization:
var repository = Startup.Container.Resolve<IRepository>();
and get your dependency.
Upvotes: 1