Lord Zed
Lord Zed

Reputation: 790

Dependency injection Scoped into Transient and then Transient into Singleton

I have a scoped Context that is being accessed from transient service through method. This transient service is being injected into singleton service.

Will my scoped Context become singleton or will it stay scoped?

public class Context : IContext
{
    public string CorrelationId { get; set; }

    public Context(string id)
    {
        CorrelationId = id;
    }
}

Context accessor:

internal class RequestContextRegistrator : IRequestContextRegistrator
{
    private IContext context;

    public IContext RegisterContext(IContext context)
    {
        this.context = context;

        return context;
    }

    public IContext Get()
    {
        return context ?? new Context()
        {
            CorrelationId = context.CorrelationId
        };
    }
}

And Singleton object:

public class QueueSender<TCommand> 
{
    private readonly IRequestContextRegistrator provider;

    public QueueSender(IRequestContextRegistrator provider)
    {
       this.provider = provider;
    }

    public async Task Send(TCommand command)
    {
        var context = provider.Get();

        var message = PrepareServiceBusMessage(command, userAgent, context?.CorrelationId);

    }
}

The whole idea is to be able to pass around context id that is unique to the particular "request". The request is not coming from dotnet controller, it comes from queue receiver class.

Or to paraphrase it, how deep does this conversion to singleton goes for tree of dependency injections.

Upvotes: 3

Views: 8445

Answers (2)

sa-es-ir
sa-es-ir

Reputation: 5102

Do not resolve a scoped service from a singleton it's so called captive dependency. It may cause the service to have incorrect state when processing subsequent requests and most likely a memory leak. It's fine to:

  • Resolve a singleton service from a scoped or transient service.
  • Resolve a scoped service from another scoped or transient service.

please see this link Service lifetime

Upvotes: 3

Johnathan Barclay
Johnathan Barclay

Reputation: 20382

Will my scoped Context become singleton or will it stay scoped?

It will stay scoped.

Your singleton instance will have a RequestContextRegistrator injected which will in turn have a Context injected; this Context instance will exist until your app terminates, as the singleton will preserve its reference, however, any other class that requires an IContext will have a new Context injected.

Upvotes: 0

Related Questions