In a recent project, I faced an issue while registering multiple implementations of the same interface in .NET CORE. I found different solutions for multiple implementations of the same interface in .NET CORE
I faced an issue with the below. I have 3 classes with 1 interface
public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService { }
public class ServiceC : IService { }
In ASP.NET Core, how do I register these services and resolve them at runtime based on some key?
Solution 1: Use of Microsoft.Extensions.DependencyInjection.
Register your services as:
services.AddSingleton<IService, ServiceA>();
services.AddSingleton<IService, ServiceB>();
services.AddSingleton<IService, ServiceC>();
Then resolve with a little of Linq:
var services = serviceProvider.GetServices<IService>();
var serviceB = services.First(o => o.GetType() == typeof(ServiceB));
or
var serviceZ = services.First(o => o.Name.Equals("Z"));
Solution 2: use of inheritance
Create a separate interface derived from the Base interface for each class. create individual interfaces that inherit from IService, implement the inherited interfaces in your IService implementations, and register the inherited interfaces rather than the base.
In this way we can have as many copies of the interface as we want and we can pick suitable names for each of them. And we have the benefit of type safety
public interface IService
{
}
public interface IServiceA: IService
{}
public interface IServiceB: IService
{}
public interface IServiceC: IService
{}
public class ServiceA: IServiceA
{}
public class ServiceB: IServiceB
{}
public class ServiceC: IServiceC
{}
Container:
container.Register<IServiceA, ServiceA>();
container.Register<IServiceB, ServiceB>();
container.Register<IServiceC, ServiceC>();
Solution 3 : Use of .NET CORE 8 Keyed DI services
Keyed DI services
Keyed dependency injection (DI) services provides a means for registering and retrieving DI services using keys. By using keys, you can scope how you register and consume services. These are some of the new APIs:
Don’t forget to leave your feedback and comments below!
Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
Blog: www.sujeetbhujbal.com
CodeProject:-https://www.codeproject.com/Members/SujitBhujbal
CsharpCorner:-http://www.c-sharpcorner.com/Authors/sujit9923/sujit-bhujbal.aspx
Linkedin :-http://in.linkedin.com/in/sujitbhujbal
Medium: - https://medium.com/@SujeetBhujbal
------------------------------------------------------------------------------