使用Unity DI的帐户控制器中的IRepositories为空

时间:2015-08-28 06:32:56

标签: c# asp.net-mvc dependency-injection unity-container asp.net-identity

我在我的应用程序中使用Unity DI。我在UnityConfig.cs文件中注册了我的存储库。

 public static void RegisterTypes(IUnityContainer container)
 {
     // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
     // container.LoadConfiguration();

     container.RegisterType<DbContext, RanoChatDbContext>(new HierarchicalLifetimeManager());
     container.RegisterType<UserManager<AppUser>>( new HierarchicalLifetimeManager());
     container.RegisterType<IUserStore<AppUser>, UserStore<AppUser>>(new HierarchicalLifetimeManager());
     container.RegisterType<AccountController>( new InjectionConstructor());
     container.RegisterType<IRepositories, Repositories>();
 }

AccountController

private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private IRepositories repos;

public AccountController()
{            
}

public AccountController(ApplicationUserManager userManager,
                         ApplicationSignInManager signInManager,
                         IRepositories Repositories)
{
    repos = Repositories;
    UserManager = userManager;
    SignInManager = signInManager;
}

但是回购是null

虽然在我的HomeController中正确地初始化了相同的repos。

IRepositories repos;

public HomeController(IRepositories repos)
{
    this.repos = repos;
}

1 个答案:

答案 0 :(得分:2)

你的3-arg构造函数可能还有Unity不知道如何注入的其他类型(ApplicationUserManager,ApplicationSignInManager),因为你没有注册这些类型。

public AccountController(ApplicationUserManager userManager,
                         ApplicationSignInManager signInManager, 
                         IRepositories Repositories)

此外,它可能只是调用控制器的零参数构造函数。告诉Unity如何通过注册以下内容来实例化控制器:

container.RegisterType<AccountController>(new InjectionConstructor(typeof(Repositories)));

请参阅MSDN - Registering Injected Parameter and Property Values