[英]How to injection dependencies into custom Identity UserStore implementation?
I have an ASP.NET Web API project using ASP.NET Identity for authentication/authorization. 我有一个使用ASP.NET Identity进行身份验证/授权的ASP.NET Web API项目。 I've inserted my own custom Identity implementation, namely my own UserStore to talk with Azure Tables, and removed the EF/SQL Server stuff.
我插入了自己的自定义Identity实现,即我自己的UserStore以与Azure Tables进行通信,并删除了EF / SQL Server内容。 However, most of the docs I see out there recommend creating an instance of the UserManagerFactory within the Startup.Auth.cs class as follows:
但是,我看到的大多数文档都建议在Startup.Auth.cs类中创建UserManagerFactory的实例,如下所示:
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. 我的CustomUserStore对另一个项目中的存储库有依赖性,我将该依赖性注入到构造函数中。
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. 但是,在Startup.Auth.cs中创建“ new CustomUserStore()”是一种反模式,无法解决依赖关系。 What is the right way to resolve this dependency when creating a UserManager?
创建UserManager时解决此依赖性的正确方法是什么? I'd like to either not have to "new up" a UserManagerFactory, or somehow resolve the dependency inline:
我想不必“新建” UserManagerFactory,或者以某种方式解决内联的依赖关系:
new UserManager<CustomUserModel>(container.Resolve<IRepository>());
Then the question becomes, how to get the single IOC container instance... 然后问题就变成了如何获得单个IOC容器实例...
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. 在global.asax或owin启动类中创建一个静态字段来保存ioc容器的引用,在容器引导程序设置中设置静态字段值。
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. 之后,您可以从某个地方访问ioc容器,在Startup.Auth.cs类中,您可以读取ioc静态字段容器并初始化内联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. 得到你的依赖
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.