为什么Unity没有选择无参数构造函数?

时间:2015-10-21 15:32:38

标签: c# inversion-of-control unity-container ioc-container

我在MVC / WebAPI应用程序中使用Unity注册了这3种类型:

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

然后类型的定义如下:

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....
}

工作正常。但是如果我向ExceptionRepository添加一个新的约束器,例如:

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

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

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

//Rest of the implementation....
}

我有一个异常说:InvalidOperationException - 无法构造String类型。您必须配置容器以提供此值

我知道解决方案是注册传递字符串的类型,例如:

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

但我不明白为什么Unity在旋转类型时没有选择无参数构造函数。我认为这将是默认行为。

0 个答案:

没有答案