ServiceProvider 未解析依赖关系,返回 null

5 .net c# dependency-injection mediator

我不明白为什么 ServiceProvider 没有获得注册服务的实例

我有以下 DI 配置

_serviceCollection.AddScoped<INotificationMediator, NotificationMediator>();
_serviceCollection.AddScoped<INotificationFactory, NotificationFactory>();
_serviceCollection.AddTransient<INotificationHandler<OrderCreatedEvent>, OrderCreatedEventHandler>();
Run Code Online (Sandbox Code Playgroud)

这应该得到正确的服务:但返回 null

public class NotificationFactory : INotificationFactory
{
    private readonly IServiceProvider _serviceProvider;

    public NotificationFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public INotificationHandler<TNotification> GetHandler<TNotification>()
        where TNotification : INotification
    {
        var handler1 = _serviceProvider.GetService(typeof(INotificationHandler<TNotification>));
        var handler2 = _serviceProvider.GetService<INotificationHandler<TNotification>>(); 

        return handler2;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我正在尝试解决的服务

public class OrderCreatedEventHandler : INotificationHandler<OrderCreatedEvent>
{
    public Task HandleAsync(OrderCreatedEvent domainEvent, CancellationToken? cancellationToken = null)
    {
        throw new System.NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是通知

public class OrderCreatedEvent : INotification { }
Run Code Online (Sandbox Code Playgroud)

我关注了 Jbogard MediatR,这是链接https://github.com/jbogard/MediatR

我在这里做错了什么,问题可能是什么?

顺便说一句,我对用例处理做了同样的事情,并且在获得正确的用例方面没有任何问题。用 IRequest 代替 INotification,所有其他部分的逻辑都是相同的

我尝试调用NotificationFactor GetHandler的方式是使用NotificationMediator

public class NotificationMediator : INotificationMediator
{
    private readonly INotificationFactory _notificationFactory;

    public NotificationMediator(INotificationFactory notificationFactory)
    {
        _notificationFactory = notificationFactory;
    }

    public Task DispatchAsync<TNotification>(TNotification notification, CancellationToken? cancellationToken = null)
        where TNotification : INotification
    {
        INotificationHandler<TNotification> notificationHandler = _notificationFactory.GetHandler<TNotification>();

        return notificationHandler.HandleAsync(notification, cancellationToken);
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是这样称呼的

aggregate.Events.ForEach(domainEvent => _eventHandler.DispatchAsync(domainEvent));
Run Code Online (Sandbox Code Playgroud)

aggregate.Events 是 INotifications 的列表

public virtual List<INotification> Events { get => _events; }
Run Code Online (Sandbox Code Playgroud)