如何注入ApplicationUserManager与统一 [英] How to inject ApplicationUserManager with unity

查看:657
本文介绍了如何注入ApplicationUserManager与统一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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; }
    }

由于某种原因,我的存储库没有被注入。 存储库总是 null

For some reason my repository in not getting injected. Repository is always null

我也有这行在我的统一配置中

I also have this line in my unity configuration

.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager())

如何注入?

更新N

这是我的控制器的代码如何我是伟大的 UserManager

That is code from my controller how I am greatig 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

UPDATE N+1:

当我发现 Unity.Mvc 包不会注入WebApi控制器。为了注入WebApi控制器,我使用了这个 mehtod 。我试图删除 Unity.Mvc pacakge,但得到身份为我的理解造成错误,因为 Unity 无法实例化一些身份类型,但是在设置 Mvc container
所以我带回了 Unity.Mvc 包将我的标识类型其他的我解释说,当 Unity 解决身份类型

As I find out Unity.Mvc package is not injecting WebApi controllers. I used this mehtod in order to inject WebApi controllers. I was trying to remove Unity.Mvc pacakge but got Identity thowing errors for my understanding because Unity was not able to instantiate some Identity types however they was being congiured and worked in case of setting Mvc container So I brought back Unity.Mvc package to inject my Idenity types otherwhise as I explained above it is throwing different kind on null refs when Unity resolving Identity types.

所以我现在有两个容器在我的项目 Unity.Mvc 注入 DependencyResolver.SetResolver(新的UnityDependencyResolver(容器)) ; 需要解决身份类型和自定义 WebApi 注入 config.DependencyResolver = new UnityResolver(container); 需要注入的Web应用程序容器,WebApi 使用同一个UnityConfig。

So I have two containers now in my project Unity.Mvc injection DependencyResolver.SetResolver(new UnityDependencyResolver(container)); that needed to resolve Identity types and custom WebApi injection config.DependencyResolver = new UnityResolver(container); container that needed to inject WebApi contorllers both using same UnityConfig.

更新3:

我已经更改
这个:

I've changed this:

app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

到这个

app.CreatePerOwinContext(() => UnityConfig.GetConfiguredContainer().Resolve<ApplicationUserManager>());

Startup.ConfigureAuth()现在我的WebApi容器是完全工作和构造所有必需的身份类型所以我可以禁用Mvc容器,甚至完全可以删除 Unity.Mvc package。

in Startup.ConfigureAuth() and now I my WebApi container is fully working and constructin all required Identity types so I can disable Mvc container or even completely can remove Unity.Mvc package.

感谢@Sam Farajpour Ghamari为大家做了很多事情。

Thanks to @Sam Farajpour Ghamari for clerifying lots of things.

推荐答案

由于您正在使用 UserManager 与OWIN。您需要将OWIN容器集成到一体。在哪里,我没有看到你的其他部分的代码特别是OWIN启动方法。我展示一个简单的例子来演示如何用自己的方式来做到这一点。

Since you are using UserManager with OWIN. You need to integrate OWIN container with unity. Where as I don't see your other part of codes specially OWIN startup method. I show a simple example to demonstrate how you can do this by own.

首先,如果您使用Entity Framework,您必须将您的上下文注册为统一。第二个注册其他类型的身份需要他们这样:

First if you are using Entity Framework you must register your context to unity. Second register other type which Identity need them like this:

container.RegisterType<DbContext, MyDbContext>(new PerRequestLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>,
    UserStore<ApplicationUser>>(new PerRequestLifetimeManager());
container.RegisterType<ApplicationUserManager>(new PerRequestLifetimeManager());
container.RegisterType<IAuthenticationManager>(
    new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication))
container.RegisterType<ApplicationSignInManager>(new PerRequestLifetimeManager());

然后更改 ApplicationUserManager 的构造函数,如下所示:

Then change constructor of ApplicationUserManager like this:

public ApplicationUserManager(IUserStore<ApplicationUser> store,
    IRepository repo)
        : base(store)
{
    this.Repository=repo;
    // put your other configuration here instead of putting in 
    // static ApplicationUserManagerCreate() method.
    this.UserValidator = new UserValidator<ApplicationUser>(this)
    {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };
        // Configure validation logic for passwords
    this.PasswordValidator = new PasswordValidator
    {
        RequiredLength = 6,
        RequireNonLetterOrDigit = true,
        RequireDigit = true,
        RequireLowercase = true,
        RequireUppercase = true,
    };

        // Configure user lockout defaults
    this.UserLockoutEnabledByDefault = true;
    this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
    this.MaxFailedAccessAttemptsBeforeLockout = 5;

    // and your other configurations
}

您的 Startup.ConfigureAuth()方法更改以下行:

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(EFDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
    // others
}

to:

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(()=> DependencyResolver.Current.GetService<ApplicationUserManager>());
    app.CreatePerOwinContext(()=> DependencyResolver.Current.GetService<ApplicationSignInManager>());
    // other configs
}

我们也不需要code> ApplicationUserManager Create()和 ApplicationSignInManager.Create()方法,我们可以轻松地删除它们,因为Unity负责创建我们课程现在

Also we don't need ApplicationUserManager Create() and ApplicationSignInManager.Create() methods anymore and we could easily remove them, since Unity takes responsibility of create our classes now.

现在我们将身份完全整合到一体。对于进一步和复杂的信息,我深感鼓励您阅读这个真棒博客文章一>。

Now we fully integrate Identity with unity. For further and complex information I deeply encourage you to read this awesome blog post.

这篇关于如何注入ApplicationUserManager与统一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆