.NET Core范围内的依赖项注入不能与MediatR一起使用

时间:2019-08-06 09:50:54

标签: c# dependency-injection .net-core mediatr

考虑以下代码:

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()的构造函数被调用?

0 个答案:

没有答案