【发布时间】:2015-11-24 03:29:48
【问题描述】:
我有这样定义的ApplicationUserManager:
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{
}
public override Task<IdentityResult> CreateAsync(ApplicationUser user, string password)
{
var result = base.CreateAsync(user, password);
//...
Repository.DoSomething(...); //Repository is null here
//..
}
[Dependency]
public IRepository Repository { get; set; }
}
由于某种原因,我的存储库没有被注入。 Repository 始终是 null
我的统一配置中也有这一行
.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager())
如何让它注入?
更新 N:
这是来自我的控制器的代码;我如何得到UserManager:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
//calling my implemintation
IdentityResult result = await UserManager.CreateAsync(...);
}
我当前的统一配置
.RegisterType<IUserStore<ApplicationUser, int>, CustomUserStore>(new HierarchicalLifetimeManager())
.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication))
.RegisterType<UserManager<ApplicationUser, int>, ApplicationUserManager>()
.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager())
.RegisterType<AccountController>(new InjectionConstructor())
.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager())
.RegisterType<ApplicationUserManager>()
更新 N+1:
我发现 Unity.Mvc 包没有注入 WebApi 控制器。我使用这个method 来注入WebApi 控制器。我试图删除Unity.Mvc 包但得到Identity 抛出错误。据我了解,因为Unity 无法实例化一些Identity types,但是在设置Mvc 容器的情况下它们正在被配置和工作。
所以我带回了Unity.Mvc 包来注入我的Identity types。否则,正如我上面解释的,当Unity 解析Identity types 时,它会在空引用上抛出不同的类型。
所以我现在在我的项目中有两个容器Unity.Mvc injection DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 需要解析Identity types 和自定义WebApi injection config.DependencyResolver = new UnityResolver(container); 容器需要注入WebApi contorllers 都使用相同的UnityConfig。
更新 3:
我变了 这个:
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
到这里
app.CreatePerOwinContext(() => UnityConfig.GetConfiguredContainer().Resolve<ApplicationUserManager>());
在 Startup.ConfigureAuth() 中,现在我的 WebApi 容器正在完全工作并构建所有必需的 Identity types,因此我可以禁用 Mvc 容器,甚至可以完全删除 Unity.Mvc 包。
感谢@Sam Farajpour Ghamari 澄清了很多事情。
【问题讨论】:
-
你如何访问
ApplicationUserManager对象实例? -
@SamFarajpourGhamari 是的,我可以进入调试我的自定义
CreateAsync()方法。但是Repository没有注入,等于null -
你是通过调用
HttpContext.GetOwinContext().Get<ApplicationSignInManager>()方法得到对象的实例吗? -
@SamFarajpourGhamari 尝试调用
var temt = HttpContext.Current.GetOwinContext();但收到错误“在上下文中找不到 owin.Environment 项。” -
我想知道您如何获得 ApplicationUserManager 本身的实例。可以提交相关代码吗?
标签: dependency-injection unity-container asp.net-identity asp.net-web-api2