0

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
boots
  • 51
  • 4
  • 2
    I'm afraid that your code doesn't show the problem. This might result in nobody being able to answer your question. You might consider updating your question and writing an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). – Steven Aug 06 '19 at 10:05
  • @Steven: I'm not sure what else to include. Part of the problem is that the handler registration is happening in the MediatR code, which isn't accessible in this context. If you have any suggestions about what's missing, I'm all ears. – boots Aug 07 '19 at 06:49
  • Reduce your code to a complete example that demonstrates the problem. Preferably create a console application, because this is something that can be ran by anyone to reproduce your issue. – Steven Aug 07 '19 at 06:52

0 Answers0