如何使用microsoft依赖注入设置复合类?

时间:2018-01-28 17:05:04

标签: c# dependency-injection .net-core

这是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();

1 个答案:

答案 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扩展方法解析所有依赖项并将它们注入到依赖类中