I cannot figure out why the ServiceProvider doesn't get an instance of the registered service
I have the following DI Configuration
_serviceCollection.AddScoped<INotificationMediator, NotificationMediator>();
_serviceCollection.AddScoped<INotificationFactory, NotificationFactory>();
_serviceCollection.AddTransient<INotificationHandler<OrderCreatedEvent>, OrderCreatedEventHandler>();
This should get the right service : but instead returns 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;
}
}
Following is the service which I'm trying to resolve
public class OrderCreatedEventHandler : INotificationHandler<OrderCreatedEvent>
{
public Task HandleAsync(OrderCreatedEvent domainEvent, CancellationToken? cancellationToken = null)
{
throw new System.NotImplementedException();
}
}
And this is the notification
public class OrderCreatedEvent : INotification { }
I've followed Jbogard MediatR, this is the link https://github.com/jbogard/MediatR
What am i doing wrong here, what might the problem be ?
Btw I've done the same for UseCases Handleing and I have no problem getting the right usecase. Instead of INotification there is IRequest and the logic is the same for all other parts
The way I'm trying to call the NotificationFactor GetHandler is using 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);
}
}
And this is called like this
aggregate.Events.ForEach(domainEvent => _eventHandler.DispatchAsync(domainEvent));
And the aggregate.Events is a list of INotifications
public virtual List<INotification> Events { get => _events; }