我有一个具有3个服务的应用程序:
看起来像这样简化:
public interface IValidatorService<T>
{
void ValidateContent(AbstractValidator<T> validator, List<T> content);
}
public class ValidatorService <T> : IValidatorService<T>
{
public void ValidateContent(AbstractValidator<T> validator, List<T> peopleContent)
{ ...does its job...}
}
public interface IPeopleService<T>
{
List<T> Convert(string json);
}
public class BossService : IPeopleService<People>
{
IValidatorService<Boss> _validatorService;
public BossService (IValidatorService<Boss> validatorService)
{
_validatorService = validatorService;
}
public List<People> Convert(string json)
{ ...does its job for boss...}
}
public class EmployeeService : IPeopleService<People>
{
IValidatorService<Employee> _validatorService;
public EmployeeService (IValidatorService<Employee> validatorService)
{
_validatorService = validatorService;
}
public List<People> Convert(string json)
{ ...does its job for employee...}
}
现在我可以的话,我很好:
var serviceProvider = new ServiceCollection()
.AddSingleton<IValidatorService<Boss>, ValidatorService<Boss>>()
.AddSingleton<IPeopleService<People>, BossService>()
.BuildServiceProvider();
var bosses = serviceProvider.GetService<IPeopleService<People>>().Convert(json);
但是实际上我想做这样的事情,尽管我的问题是它如何才能知道分别为老板和员工执行哪种实现,因为在这种情况下它们是同一类型IPeopleService
var serviceProvider = new ServiceCollection()
.AddSingleton<IValidatorService<Boss>, ValidatorService<Boss>>()
.AddSingleton<IPeopleService<People>, BossService>()
.AddSingleton<IValidatorService<Employee>, ValidatorService<Employee>>()
.AddSingleton<IPeopleService<People>, EmployeeService>()
.BuildServiceProvider();
var bosses = serviceProvider.GetService<IPeopleService<People>>().Convert(json);
var employees = serviceProvider.GetService<IPeopleService<People>>().Convert(json);
答案 0 :(得分:0)
不是。根据您使用的DI引擎,这将引发某种歧义的解析异常,或者某些较慢的实现可能会采用第一个。其他一些甚至允许您通过IEnumerable机制获取IPeopleService
为什么DI引擎会知道您想要哪一个?您尚未提供用于决策的任何上下文。
您必须创建一个IPeopleService
编辑:工具包很重要……某些DI引擎支持按名称或其他类型的上下文进行解析。
答案 1 :(得分:0)