Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - How to add MVC 5 authentication to Unity IoC?

I'm currently working on implementing the new ASP.NET MVC 5 out-of-the box authentication into my application. However when using Unity as my IoC, I cannot use any portion of the AccountController because I'm given the error:

The type IUserStore`1 does not have an accessible constructor.

This is my given unity setup which is called in the 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;
    }
}

And here are the default constructors of a fresh 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;
}

And here are the items being called in the AccountController constructors. These are the defaults with new names.

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

    }
}

public class ApplicationUser : IdentityUser
{

}

Any help would be widely appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with Wiktor.

You could register the parameterless constructor with Unity though and stop it taking the longer parameter by doing this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...