0

I have these 3 type registered with Unity in a MVC/WebAPI application:

container.RegisterType<ILogServices, LogServices>();
container.RegisterType<IExceptionRepository, ExceptionRepository>();
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new ExceptionLoggerHandler(container.Resolve<ILogServices>()));

Then the definition of the types is as following:

public class ExceptionLoggerHandler : ExceptionLogger
{
    private readonly ILogServices _exceptionsServices;

    public ExceptionLoggerHandler(ILogServices exceptionsServices)
    {
        _exceptionsServices = exceptionsServices;
    }

//Rest of the implementation....
}

public class LogServices: ILogServices
{
    private readonly IExceptionRepository _exceptionRepo;

    public LogServices(IExceptionRepository exceptionRepository)
    {
        _exceptionRepo = exceptionRepository;
    }

//Rest of the implementation....
}

public class ExceptionRepository: BaseRepository, IExceptionRepository
{
    private readonly string _connectionString;

    public ExceptionRepository()
    {
        _connectionString = SettingManager.AppDatabaseConnection;
    }

//Rest of the implementation....
}

That is working fine. But if I add a new constractor to ExceptionRepository, for instance:

public class ExceptionRepository: BaseRepository, IExceptionRepository
{
    private readonly string _connectionString;

    public ExceptionRepository()
    {
        _connectionString = SettingManager.AppDatabaseConnection;
    }

    public ExceptionRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

//Rest of the implementation....
}

I got an exception saying: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value

I know the solution is to register the type passing the string as the exception said:

container.RegisterType<SqlRepo.ExceptionRepository>(new InjectionConstructor(SettingManager.AppDatabaseConnection));

But I do not understand why Unity is not picking up the parameterless constructor when is revolving the type. I thought it would be the default behavior.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
osotorrio
  • 960
  • 1
  • 11
  • 30

0 Answers0