Make sure the controller has an immortal public constructor in Unity

I had a problem with the controller:
An error occurred while trying to create a controller of type '* .WebMvc.Controllers.HomeController'. Make sure that the controller does not have a constructor without parameters.

Find a solution for ApiController, but nothing was found about the normal controller.

Created a new MVC 4 project from scratch.

HomeController.cs:

public class HomeController : Controller { private IAccountingUow _uow; public HomeController(IAccountingUow uow) { _uow = uow; } 

UnityDependencyResoler.cs:

 public class UnityDependencyResolver : IDependencyResolver { private IUnityContainer _container; public UnityDependencyResolver(IUnityContainer container) { _container = container; RegisterTypes(); } 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 null; } } private void RegisterTypes() { _container.RegisterType<IAccountingUow, AccountingUow>(); } } 

Global.asax

  protected void Application_Start() { //Omitted DependencyResolver.SetResolver( new UnityDependencyResolver( new UnityContainer())); } 

It is debugged and it turns out that IAKountingUow attempts are not even made.

What am I doing wrong? Thinking about it all day.

+6
c # dependency-injection asp.net-mvc-4 unity-container
Nov 12 '12 at
source share
2 answers

Found where the problem is. Perhaps someone will face the same. The problem is that Unity was not able to resolve IAccountingUow due to the hierarchical dependency on the interfaces.

AccountingUow class has two conductors

  public AccountingUow( IRepositoryProvider repositoryProvider) { Init(repositoryProvider); } public AccountingUow() { Init( new RepositoryProvider(new RepositoryFactories()) ); } 

The Resolver dependency is not smart enough to accept a constructor without default parameters. He tries to take an interface-dependent constructor and cannot solve it, because there are no rules for resolving it.

I commented on an interface-dependent constructor and everything worked fine.

I will write a resolver for the first constructor later, maybe someone will use it.

+6
Nov 13 '12 at 9:50
source share

This can also be caused by an exception in the constructor with an external type parameter that is allowed. Constructor dependencies of this type can be successfully resolved, but if there is an exception in the external constructor, Unity will report this as " Type Test.Controllers.MyControllerWithInjectedDependencies does not have a default constructor."

+2
Nov 15 '16 at 2:29
source share



All Articles