Search code examples
c#asp.netdependency-injectionasp.net-core

Create two singleton services that implement the same interface


I have an ASP.NET Core project (my first) that requires two internal "sequencers" for specific tasks. The first was implemented like this:

In Startup.cs ConfigureServices method:

services.AddSingleton<ISequencer, ProfileSequencer>();

And of course I have the interface and implementation defined, and it's working well. However I'm not sure how to add the second sequencer, which implements the same interface but has a slightly different implementation.

services.AddSingleton<ISequencer, ChargeSequencer>();

ASP.NET doesn't complain about this, but now when I inject ISequencer into my classes, I can't imagine how it knows which singleton to use. I suspect (but don't know for sure) that the second singleton effectively replaces the first.

There is probably some bad design decision here, so I'll accept an answer that describes how I can inject two different singletons that implement the same interface, or if necessary another reasonable approach to this problem. Thanks!


Solution

  • It is not possible to register two services of same interface - second registration would override first. But I suggest you quick solution of your problem:

    1) Create nested interfaces and use them for registration:

    ISomeSpecificSequencer : ISequencer {}
    IOtherSpecificSequencer : ISequencer {}
    

    2) Use factory pattern

    interface ISequencerFactory
    {
      ISequencer GetSequencer(ISequencerOptions someOptions)
    }
    

    So in your code you inject ISequencerFactory and then use some option (it could be string, enum, Type, etc) to determine which class you need