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.