Wednesday, June 20, 2018

ASP.NET Core : FromServices Attribute

In this post let’s have a look at what FromServices attribute in ASP.NET Core brings in to the table.

Imagine I have the following interface and its implementation.
public interface IMyService
{
    string SayHello(string name);
}
 
public class MyService : IMyService
{
    public string SayHello(string name)
    {
        return $"Hello {name}";
    }
}
And I have IMyService registered with ASP.NET Core Services.
services.AddTransient<IMyService, MyService>();
Now imagine, I want to use IMyService.SayHello() method and in one of my controllers, but it’s going to be used in one single action.

Usually what we would be doing is, use constructor injection.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IMyService myService;
 
    public ValuesController(IMyService myService)
    {
        this.myService = myService;
    }
 
    [HttpGet("{name}")]
    public ActionResult<string> Get(string name)
    {
        return myService.SayHello(name);
    }
}
This looks fine, but if myService is going to be used only in Get(string name) action, having a separator field for IMyService and complicating constructor is really unnecessary.

In these type of situations, FromServices attribute is really handy.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet("{name}")]
    public ActionResult<string> Get([FromServices] IMyService myService, string name)
    {
        return myService.SayHello(name);
    }
}
So when we decorate the parameter with FromServices attribute, the framework will look up the services container and inject the matching implementation. No need to do constructor injection at all. After all parameter injection is one of the ways we can do DI.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment