如何将MVC 5身份验证添加到Unity IoC?

Jon*_*las 22 c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我正在努力在我的应用程序中实现新的ASP.NET MVC 5开箱即用身份验证.但是当使用Unity作为我的IoC时,我不能使用AccountController的任何部分,因为我给出了错误:

类型IUserStore`1没有可访问的构造函数.

这是我给出的统一设置,在global.asax中调用

public class DependencyConfig
{
    public static void Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        container.RegisterType<IEmployeeRepository, EmployeeRepository>();

        container.RegisterType<ITeamRepository, TeamRepository>();

        container.RegisterType<ICompanyRepository, CompanyRepository>();

        return container;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是新的AccountController.cs的默认构造函数

public AccountController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new BusinessTrackerUsersContext())))
{

}

public AccountController(UserManager<ApplicationUser> userManager)
{
    UserManager = userManager;
}

public AccountController(UserManager<ApplicationUser> userManager)
{
    UserManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)

以下是AccountController构造函数中调用的项目.这些是具有新名称的默认值.

public class BusinessTrackerUsersContext : IdentityDbContext<ApplicationUser>
{
    public BusinessTrackerUsersContext()
        : base("DefaultConnection")
    {

    }
}

public class ApplicationUser : IdentityUser
{

}
Run Code Online (Sandbox Code Playgroud)

任何帮助将受到广泛赞赏!

hut*_*oid 33

我同意Wiktor.

您可以使用Unity注册无参数构造函数,并通过执行以下操作停止它获取更长的参数:

container.RegisterType<AccountController>(new InjectionConstructor());
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的帮助!这正是我追求的. (2认同)

Wik*_*hla 23

因为你的控制器上有两个构造函数,所以unity将选择具有较长参数列表的构造函数,后者.它需要注入UserManager.

虽然你没有在这里列出它,但我怀疑它是唯一一个需要IUserStore的构造函数.Unity试图解决它,找不到它可以直接使用的任何构造函数或解析它的参数.