Asp.net-Mvc

如何使用 Ninject 注入身份類?

  • May 12, 2017

我正在嘗試在課程中使用 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;
   }
}

但是我不能對 UserManager 做同樣的事情(它會拋出之前顯示的錯誤):

public class AnunciosService : IAnunciosService
{
   private IGenericRepository<Anuncio> _repo;
   private ApplicationUserManager _userManager;

   public AnunciosService(IRepositorioGenerico<Anuncio> repo, ApplicationUserManager userManager)
   {
       _repo = repo;
       _userManager = 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 的答案對我不起作用,因為我使用的是一個自定義ApplicationUser類,它long作為鍵而不是string.

因此,我創建了一個通用靜態方法,它將OwinContext從目前獲取HttpContext並返回所需的具體實現。

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

引用自:https://stackoverflow.com/questions/29089877