Asp.Net Core: register implementation with multiple interfaces and lifestyle Singleton

Solution 1:

The service collection by definition is a collection of ServiceDescriptors, which are pairs of service type and implementation type.

You can however get around this by creating your own provider function, something like this (thanks user7224827):

services.AddSingleton<IInterface1>();
services.AddSingleton<IInterface2>(x => x.GetService<IInterface1>());

More options below:

private static MyClass ClassInstance;

public void ConfigureServices(IServiceCollection services)
{
    ClassInstance = new MyClass();
    services.AddSingleton<IInterface1>(provider => ClassInstance);
    services.AddSingleton<IInterface2>(provider => ClassInstance);
}

Another way would be:

public void ConfigureServices(IServiceCollection services)
{
    ClassInstance = new MyClass();
    services.AddSingleton<IInterface1>(ClassInstance);
    services.AddSingleton<IInterface2>(ClassInstance);
}

Where we just provide the same instance.

Solution 2:

You can wrap user7224827's answer to create a nice extension method matching your original desired API:

    public static class ServiceCollectionExt
    {
        public static void AddSingleton<I1, I2, T>(this IServiceCollection services) 
            where T : class, I1, I2
            where I1 : class
            where I2 : class
        {
            services.AddSingleton<I1, T>();
            services.AddSingleton<I2, T>(x => (T) x.GetService<I1>());
        }
    }

Solution 3:

Another option to keep the DI mechanism is to do as following:

services.AddSingleton<MyClass>();
services.AddSingleton<Interface1>(p => p.GetRequiredService<MyClass>());
services.AddSingleton<Interface2>(x => x.GetRequiredService<MyClass>());