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

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.

Leave a Comment