Search code examples
c#dependency-injectionasp.net-coreinversion-of-control

How to register the same service with different interfaces but the same lifecycle in .NET?


Considering the following interface and class definitions:

public interface IInterface1 { }
public interface IInterface2 { }
public class MyClass : IInterface1, IInterface2 { }

is there any way to register one instance of MyClass with multiple interfaces like this:

...
services.AddSingleton<IInterface1, IInterface2, MyClass>();
...

and resolve this single instance of MyClass with different interfaces like this:

IInterface1 interface1 = app.ApplicationServices.GetService<IInterface1>();
IInterface2 interface2 = app.ApplicationServices.GetService<IInterface2>();

Solution

  • 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.