Search code examples
c#.netasp.net-mvcinversion-of-controlunity-container

Unity container can't resolve my class


I am trying to implement Unity as an IoC container in a learning project I am working on. I have a layered application, UI->Service->Logic->DataAccess.

It's an MVC Application on the UI side.

In my controller, I have a constructor:

public HomeController()
{
    _container = new UnityContainer();
    _container.RegisterType<IUserService, UserService>();
    _container.RegisterType<IUserLogic, UserLogic>();
}

I then attempt to use the IService in one of my methods:

var service = _container.Resolve<IUserService>();
ReplyDto reply = service.Login(model.Email, model.Password);

But then get this error:

Resolution of the dependency failed, type = "Services.IUserService", name = "(none)".

I'm not sure why it's saying this. Do I maybe have an issue with MVC and the constructor? Breakpoint on the Resolve line shows that the _container does have the interface I am trying to resolve.

My UserService class has this in the constructor:

private IUserLogic _userlogic;

public UserService(IUserLogic logic)
{
    _userlogic = logic;
}

The Logic layer class is defined like this:

public class UserLogic : IUserLogic
{
    public ILog _logger;
    public IData _data;

    public UserLogic(IData data, ILog logger)
    {
        _data = data;
        _logger = logger;
    }

I am still in the process of propagating the IoC patter down through all layers.

And finally, the data access layer is defined as:

public class Data :IData
{
    Log _logger = new Log();
    MyEntities entities;
    public Data()
    {
        entities = new MyEntities();
        var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
    }

My _container has reference to the IUserLogic interfaces and which concrete class to use.


Solution

  • UserLogic(IData data, ILog logger) - neither IData nor ILog shown as registered in container - so if code is exactly like you have in the post it is the reason why IUserLogic can't be resolved when unity tries to pass argument to UserService(IUserLogic) constructor.

    Fix: register all dependencies (recursively)

    To achieve that consider:

    • make sure types with no dependencies has constructors without arguments
    • register instances instead of types - if that works for your system
    • make constructors depend on concrete types (as all concrete types by default registered with Unity) - not testable choice...
    • provide parameters for all non-interface/non class arguments like int/string (How resolve a dependency with unity passing arguments in the constructor?)