Home > OS >  Dependency injection pattern for polymorphism in ASP.NET
Dependency injection pattern for polymorphism in ASP.NET

Time:12-11

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?

CodePudding user response:

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.

  • Related