1

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?

8
  • Then this method is good candidate to move it to the own controller. And pass dependency through constructor Commented Nov 15, 2016 at 7:37
  • @Fabio Not in my case, no. Commented Nov 15, 2016 at 7:38
  • Then what is wrong with passing dependency through constructor of current controller if you stricted to use only one controller Commented Nov 15, 2016 at 7:39
  • 1
    Dependencies can be passed to the instance in three ways(what I know at this moment) constructor, method and property. In case of ASP.NET method and property not easy approach so you have only constructor. For example if you make dependency a public property then you can set it in middle-ware only for this method - but this makes your code more complex to maintain Commented Nov 15, 2016 at 7:46
  • @Fabio Okay that's what I needed to know. I can't find proper documentation for ASP.NET Core container. They only talk about constructor injection. I hope there is a simple way to do non-constructor way. Commented Nov 15, 2016 at 7:53

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

They upgraded the docs site, so I missed that! Thanks! This is exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.