0

I am reading about DI pattern in ASP.NET. I know it can create a instance inside another class. For example, we have class HomeController need to have service instance like this:

class HomeController{
   private IService service;
   public HomeController(IService s){
     this.service = s;
   }
}

IService is implemented by WaterService class.

And we have code to register class which can be created instance, the instance can be type of transient, scope or singleton:

using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IService , WaterService>();
var app = builder.Build();

Then I realize, if IService is implemented by both class WaterService and ElectricService, I have some situation, for example:

Call api to url .../service/waterService: show infomation of waterService.

Call api to url .../service/electricService: show inffomation of electricServic.

how can we register one of these class instance base on situation?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • If there is at least one method in `IService` that is not implemented by either `WaterService` or `ElectricService`, then you would need to have separate services for both, because you will not want to break [interface segregation principle](https://en.wikipedia.org/wiki/Interface_segregation_principle). That said, I believe [this question](https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core) has what you are looking for. – Isaac Ikusika Dec 09 '22 at 03:21
  • Does this answer your question? [Conditional dependency resolver on run-time (.net Core)](https://stackoverflow.com/questions/57758285/conditional-dependency-resolver-on-run-time-net-core) – Guru Stron Dec 13 '22 at 09:56

1 Answers1

0

I had some problem but resolved by help of The Answer was given by Shahar Shokrani

Let me know if still facing to implement DI.

Pradeep Kumar
  • 1,193
  • 1
  • 9
  • 21
  • well, most answer recommend using factory pattern, create a factory interface and inject factory class, then create concrete class base on situation. – Ma Việt Tùng Dec 10 '22 at 09:19