我已经创建了界面,将控制器与具体实现区分开来:
private IUserRepository _userRepository;
public AccountController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
并设置类型注册:
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<IUserRepository, UserRepository>();**
// asp identity
container.RegisterType<IUserStore<ApplicationUser, int>, UserStoreIntPk>();
container.RegisterType<UserManager<ApplicationUser, int>>();
container.RegisterType<DbContext, ApplicationDbContext>();
container.RegisterType<ApplicationUserManager>();
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
}
但我在控制器中的私有变量_userRepository始终为null! 为什么?我该如何解决?
EDIT1:Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//var factory = new CustomControllerFactory();
//ControllerBuilder.Current.SetControllerFactory(factory);
UnityWebActivator.Start();
}
答案 0 :(得分:0)
我发现了错误的原因。我的控制器有多个构造函数。 Unity选择了具有最大参数的构造函数(最长的一个)。而且我的构造函数不是我的依赖参数。
所以,我调整了初始构造函数以获取我的附加参数。
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, IUserRepository userRepository)
现在一切正常。