I have service which implements multiple Interfaces; for example
ServiceClass : IService1, IService2
{
// implementation
}
Now I need to register this service in ConfigureServices() in such a way that I have a single instance of SerivceClass and this instance can be used even if the IService1 or IService2 is injected via constructor. For ex,
public class SomeClass1: ISomeClass1
{
SomeClass1(IService1 service)
{
...
}
}
public class SomeClass2 : SomeClass2
{
SomeClass2(IService2 service)
{
...
}
}
I have tried registering the ServiceClass using its both Interfaces in ConfigureServices() but it would create multiple instances.
ConfigureServices(){
...
services.AddSingleton<IService1, ServiceClass>();
services.AddSingleton<IService2, ServiceClass>();
services.AddSingleton<ISomeClass1>(
x => new SomeClass1(
x.GetRequiredService<IService1>(),
));
services.AddSingleton<ISomeClass2>(
x => new SomeClass2(
x.GetRequiredService<IService2>(),
));
....
}
I need to find a solution where I can inject the same instance to SomeClass1 and SomeClass2 eventhough the injected interfaces are different.
CodePudding user response:
One way to solve this is to register the implementing class, and then explicitly resolve the multiple interfaces from that:
services.AddSingleton<ServiceClass>();
services.AddSingleton<IService1, ServiceClass>(x => x.GetRequiredService<ServiceClass>());
services.AddSingleton<IService2, ServiceClass>(x => x.GetRequiredService<ServiceClass>());
There's an example of this approach used here for HttpClientFactory for example.
