Consider the following code:
Startup.cs
public static void RegisterServices(IServiceCollection services)
{
services.AddSingleton<IEventBus, RabbitMQBus>();
services.AddTransient<IStuff, Stuff>(); // Empty/dummy interface and class
services.AddMediatR(typeof(AnsweredQuestionCommandHandler));
}
RabbitMQBus.cs
public sealed class RabbitMQBus : IEventBus
{
private readonly IMediator _mediator;
private readonly Dictionary<string, List<Type>> _handlers;
private readonly List<Type> _eventTypes;
private readonly IServiceScopeFactory _serviceScopeFactory;
public RabbitMQBus(IMediator mediator, IServiceScopeFactory serviceScopeFactory)
{
_mediator = mediator;
_serviceScopeFactory = serviceScopeFactory;
_handlers = new Dictionary<string, List<Type>>();
_eventTypes = new List<Type>();
}
public Task SendCommand<T>(T command) where T : Command
{
return _mediator.Send(command);
}
...
}
AnsweredQuestionCommandHandler.cs
public class AnsweredQuestionCommandHandler : IRequestHandler<QuestionAnsweredCommand, bool>
{
private readonly IEventBus _bus;
private readonly IStuff _stuff;
public AnsweredQuestionCommandHandler(IEventBus bus, IStuff stuff)
{
_bus = bus;
_stuff = stuff;
}
...
}
Can someone explain why injecting a Stuff
with Transient or Singleton lifetime works as expected--when SendCommand()
is invoked, the constructor for AnsweredQuestionCommandHandler
is called, Stuff
is injected--but if inject it with Scoped lifetime, not only is Stuff
never injected, but in fact the constructor for AnsweredQuestionCommandHandler
is never even called when SendCommand()
is invoked?