grokky
grokky

Reputation: 9255

How do I get a dependency needed in one method only, using ASP.NET Core

I've registered my FooBar type with ASP.NET's built-in container.

I need an instance in one of my action methods. If I needed it in all of the controller's actions, then I'd inject it into the constructor. But I only need it in one action method.

So in the action method, I assume I could do this (untested):

var service = HttpContext.RequestServices.GetService(typeof(FooService)) as FooService;

But the docs say that is is a bad idea. I agree.

So what are my options?

Upvotes: 1

Views: 391

Answers (1)

adem caglin
adem caglin

Reputation: 24063

You can use FromServices attribute to inject a dependency into an action:

public IActionResult SampleAction([FromServices]FooService fooService)
{
   // ...
}

Sometimes you don't need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices] as shown here:

See official docs: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection#action-injection-with-fromservices

Upvotes: 5

Related Questions