考虑以下代码:
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;
}
...
}
有人可以解释为什么向瞬态或单例生命周期注入Stuff
可以按预期方式工作-调用SendCommand()
时,调用AnsweredQuestionCommandHandler
的构造函数,Stuff
被注入了-但是如果以Scoped生命周期注入它,不仅不会注入Stuff
,而且实际上甚至在AnsweredQuestionCommandHandler
时都不会调用SendCommand()
的构造函数被调用?