我不知道为什么ServiceProvider无法获得注册服务的实例
我具有以下DI配置
_serviceCollection.AddScoped<INotificationMediator, NotificationMediator>();
_serviceCollection.AddScoped<INotificationFactory, NotificationFactory>();
_serviceCollection.AddTransient<INotificationHandler<OrderCreatedEvent>, OrderCreatedEventHandler>();
这应该得到正确的服务:但是返回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;
}
}
以下是我要解决的服务
public class OrderCreatedEventHandler : INotificationHandler<OrderCreatedEvent>
{
public Task HandleAsync(OrderCreatedEvent domainEvent, CancellationToken? cancellationToken = null)
{
throw new System.NotImplementedException();
}
}
这是通知
public class OrderCreatedEvent : INotification { }
我关注了Jbogard MediatR,这是链接https://github.com/jbogard/MediatR
我在这里做错什么了,可能是什么问题?
顺便说一句,我已经为UseCases Handleing做过同样的事情,并且我也没有遇到任何问题。除了INotification之外,还有IRequest,其他所有部分的逻辑都相同
我试图调用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);
}
}
这个叫做
aggregate.Events.ForEach(domainEvent => _eventHandler.DispatchAsync(domainEvent));
aggregate.Events是INotifications的列表
public virtual List<INotification> Events { get => _events; }