这是dotnet.core问题
让我说我有NotifierResolver类:
public class NotifierResolver : INotifierResolver
{
private readonly List<INotifier> _notifiers;
public NotifierResolver(List<INotifier> notifiers)
{
_notifiers = notifiers;
}
public INotifier Resolve(INotification notification)
{
var notifier = _notifiers.Single(h => h.CanNotify(notification));
if (notifier == null)
{
throw new Exception($"could not resolve notification: {notification.GetType()}");
}
return notifier;
}
}
如何在服务集合(Microsoft.Extensions.DependencyInjection)下设置它的依赖项?
var serviceProvider = new ServiceCollection()
.????
.AddSingleton<INotifierResolver, NotifierResolver>()
.BuildServiceProvider();
答案 0 :(得分:3)
您可能需要在组合根处构建复合,如下所示。
var serviceProvider = new ServiceCollection()
.AddTransient<INotifier, SomeNotifier>()
.AddTransient<INotifier, SomeOtherNotifier>()
.AddTransient<INotifier, YetAnotherNotifier>()
.AddSingleton<INotifierResolver, NotifierResolver>(_
=> new NotifierResolver(_.GetServices<INotifier>().ToList())//<-- Note GetServices
)
.BuildServiceProvider();
因此,假设您在服务集合中注册了多个INotifier
,在解析INotifierResolver
时,提供程序通过IServiceProvider.GetServices
扩展方法解析所有依赖项并将它们注入到依赖类中