Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add MVC 5 authentication to Unity IoC?

Tags:

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!

like image 278
Jon Douglas Avatar asked Nov 16 '13 19:11

Jon Douglas


People also ask

What is IoC in MVC C#?

Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

What is container resolver unity?

You can use the Unity container to generate instances of any object that has a public constructor (in other words, objects that you can create using the new operator). When you call the Resolve method and specify the type that is not registered, the container simply generates and returns an instance of that type.


1 Answers

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()); 
like image 114
hutchonoid Avatar answered Sep 27 '22 19:09

hutchonoid