SKumar SKumar - 3 months ago 29
ASP.NET (C#) Question

Cannot resolve the controller

Previously I was not using an interface for my generic repository. When I extracted the interface from my generic repository, I added two constructors: a parameterless and a parameterized constructors I am getting the following error:

{"Resolution of the dependency failed, type = \"NascoBenefitBuilder.Controllers.ODSController\", name = \"(none)\".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, ControllerLib.Models.Generic.IGenericRepository, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving NascoBenefitBuilder.Controllers.ODSController,(none)
Resolving parameter \"repo\" of constructor NascoBenefitBuilder.Controllers.ODSController(ControllerLib.Models.Generic.IGenericRepository repo)
Resolving ControllerLib.Models.Generic.IGenericRepository,(none)"}


My Controller at the beginning:

public class ODSController : ControllerBase
{
IGenericRepository _generic = new GenericRepository();
}


After extracting the interface and use it in controller:

public class ODSController : ControllerBase
{
IGenericRepository _generic;
public ODSController() : this(new GenericRepository())
{
}

public ODSController(IGenericRepository repo)
{
_generic = repo;
}
}


When I use parameterized constructor it is throwing error mentioned above.

Can anyone help me to overcome this problem?

Answer

You no longer need the default constructor:

public class ODSController : ControllerBase
{
    private readonly IGenericRepository _repository;
    public ODSController(IGenericRepository repository)
    {
        _repository = repository;
    }
}

And then make sure you've properly configured your Unity container:

IUnityContainer container = new UnityContainer()
    .RegisterType<IGenericRepository, GenericRepository>();

And that you are using the Unity controller factory in Application_Start:

ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
Comments