grokky grokky - 1 year ago 74
ASP.NET (C#) Question

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

I've registered my

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?

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download