我正在尝试在类中使用UserManager,但是我收到此错误:
Error activating IUserStore{ApplicationUser}
No matching bindings are available, and the type is not self-bindable.
我使用的是默认的 Startup.cs,它为每个请求设置一个实例:
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
我能够获得 ApplicationDbContext 实例,我相信它是由 Owin 注入的(这是真的吗?):
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private ApplicationDbContext context;
public GenericRepository(ApplicationDbContext context)
{
this.context = context;
}
}
但是我不能对用户管理器做同样的事情(它抛出了前面显示的错误):
public class AnunciosService : IAnunciosService
{
private IGenericRepository<Anuncio> _repo;
private ApplicationUserManager _userManager;
public AnunciosService(IRepositorioGenerico<Anuncio> repo, ApplicationUserManager userManager)
{
_repo = repo;
_userManager = userManager;
}
}
控制器像这样使用用户管理器:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
我正在使用 ninject 来注入我的其他类,但是我如何向 UserManager 注入它的依赖项并避免在我的控制器中像这样使用它?
我像这样注入它
kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>();
kernel.Bind<UserManager<ApplicationUser>>().ToSelf();
现在它正在正常工作。
OP 的答案对我不起作用,因为我使用的是将long
作为键而不是string
的自定义ApplicationUser
类。
因此,我创建了一个通用静态方法,该方法将从当前HttpContext
获取OwinContext
并返回所需的具体实现。
private static T GetOwinInjection<T>(IContext context) where T : class
{
var contextBase = new HttpContextWrapper(HttpContext.Current);
return contextBase.GetOwinContext().Get<T>();
}
然后我使用GetOwinInjection
方法进行注射,如下所示:
kernel.Bind<ApplicationUserManager>().ToMethod(GetOwinInjection<ApplicationUserManager>);
kernel.Bind<ApplicationSignInManager>().ToMethod(GetOwinInjection<ApplicationSignInManager>);
如果你也在使用 IAuthenticationManger
,你应该像这样注入它:
kernel.Bind<IAuthenticationManager>().ToMethod(context =>
{
var contextBase = new HttpContextWrapper(HttpContext.Current);
return contextBase.GetOwinContext().Authentication;
});