我有以下构造函数(只有一个用于 Controller ):
[Authorize]
public class AccountController : Controller
{
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,
IAccountService accountSrv)
{
UserManager = userManager;
SignInManager = signInManager;
AccountService = accountSrv;
}
private IAccountService AccountService { get; }
private ApplicationSignInManager SignInManager { get; }
private ApplicationUserManager UserManager { get; }
我希望 MVC 使用正确的参数来调用它,所以我尝试了以下方法:
Global.asax.cs
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DALMapper.Mapping();
LabMapper.Mapping();
var container = new UnityContainer();
container
.RegisterType<IDALContext, DALContext>()
.RegisterType<IConsultantService, ConsultantService>()
.RegisterType<IProjectService, ProjectService>()
.RegisterType<IAccountService, AccountService>()
.RegisterType<AccountController, AccountController>()
.RegisterType<ApplicationUserManager, ApplicationUserManager>()
.RegisterType<ApplicationSignInManager, ApplicationSignInManager>()
.RegisterInstance<IAccountService>(new AccountService(new DALContext()), new ContainerControlledLifetimeManager())
;
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
(UnityDependencyResolver 是:)
public class UnityDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
我在其中注册所需的每种类型(尽管输入/来自类型相同(我对 Unity 还很陌生),但结果感觉很奇怪)。
但是这不起作用。 (据我所知,从MV3开始,默认的 Controller 工厂将使用服务定位器,因此不需要实现自己的工厂)。
出了什么问题?
当前结果:
Server Error in '/' Application.
No parameterless constructor defined for this object.
最佳答案
如果我正确理解您的问题,则解决 ApplicationUserManager 和 ApplicationSignInManager 的依赖关系时存在问题。 这是为我解决问题的代码:
//for accountcontroller
container.RegisterType<DbContext, ApplicationDBContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));
关于c# - Unity IOC,无法修复无参数构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411219/