Search This Blog

2020/12/10

FromServices Attribute in ASP.NET Core

 We are do Dependency injection directly into controller action using FromServices attribute.

Lets see how we can accomplish this.I have a ASP.NET Core WebAPI Project which i will use for demonstration purpose.

First we create a service & its interface as follows

IRainService.cs

public interface IRainService

{

int GetRainEstimate(string location);

}

RainService.cs

public class RainService : IRainService

{

public int GetRainEstimate(string location)

{

     //logic to dynamically get Rain Forecast

      return 10;

}

}


Now we can these to classes straightly head to ConfigureServices in startup.cs

StartUp.cs


public void ConfigureServices(IServiceCollection services)

{


services.AddControllers();

services.AddTransient<IRainService, RainService>();

}


Now in Our Controller Action we add IRainService as method parameter with FromService attribute as follows.


WeatherForecastController.cs


public IEnumerable<WeatherForecast> Get([FromServices] IRainService RainService)

{

var rainInMlmtr = RainService.GetRainEstimate("mumbai");

//other code of controller

}


Inside this action method we can now access RainService class and call its method & property due to Dependency Injection in Controller Action.





No comments:

Post a Comment