I know how to inject into controller actions and the controller directly, by adding the service to the IServiceprovider and then the framework just handles it for me and in the case of controller actions I could add [Microsoft.AspNetCore.Mvc.FromServices]
and it would inject the service to the specific action.
But that requires my controller to know specifically what the underlying parameter would need, which is a coupling I find unnecessary and potentially harmful.
I would like to know if it is possible to have something close to the following:
[HttpPost]
public async Task<ActionResult> PostThings([FromBody]ParameterClassWithInjection parameter) {
parameter.DoStuff();
...}
public class ParameterClassWithInjection{
public readonly MyService _myService;
public ParameterClassWithInjection(IMyService service){ _myService = service;}
public void DoStuff(){ _myService.DoStuff(); }
}
I have only found something about a custom model binder in the docs. https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-3.1#custom-model-binder-sample
This shows how you can create a custom binder and have a custom provider supply the injection. It just seems I need to implement a lot of boilerplate code from the automatic binding (which works absolutely fine for me in every case) in order to get some dependency injection.
I would hope you could point me in a better direction or put my quest to a rest if this is the only option.