'C# IServiceScopeFactory - Multiple singleton instances of same type

I have an application which uses a external library to create a client instance for a Db Provider.

This dependency is added as Singleton to my app DI container, and have some parameters which are passed from my app to the initialization constructor of the library.

I need to create another client with different arguments, theoretically can this be achieved? By my knowledge is that I have to add another singleton class with different arguments to the DI (I am using .NET core IServiceScopeFactory), but how I can resolve the one I need, if both have the same Types.



Solution 1:[1]

you can register Provider Factory as singleton then use it to create your clients

public class DBProviderFactory
{
    private static ClientType _clientA { get; set; }
    private static ClientType _clientB { get; set; }
    private static readonly object ThreadLock = new object();

    public ClientType GetInstanceA()
    {
        if (_clientA != null)
        {
            return _clientA;
        }
        lock (ThreadLock)
        {
            _clientA = new DbInitializer("1", "2");
        }
        return _clientA;
    }
    public ClientType GetInstanceB()
    {
        if (_clientB != null)
        {
            return _clientA;
        }
        lock (ThreadLock)
        {
            _clientB = new DbInitializer("3", "4");
        }
        return _clientB;
    }
}

first register it

services.AddSingleton<DBProviderFactory>();

then use it as below

public class service
{
    private ClientType client { get; set; }
    public service(DBProviderFactory dBProviderFactory)
    {
        client = dBProviderFactory.GetInstanceA();
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ehsan Kenari