dotnet / dotnet/AspNetCore.Docs

Document that [FromServices] works on MVC Controller properties.

Open
#35,811 2 comments 0 reactions 1 assignee Claimed by @tdykstra View on GitHub
:watch: Not Triaged
Dominant language
C#
Stars
13.1k
Forks
24.6k
Avg merge
1d 2h
Merged PRs (30d)
109

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

Ive been working on various ASP.NET Core projects, and Ive noticed that in basically every controller an ILogger gets injected. It starts to feel super repetitive when you have a lot of controllers or services.

### Describe the solution you'd like

Ive tried to implement this idea using reflection, but considering the downsides i think a source generator would be better suited for this idea. I have a somewhat basic understanding how source generators work. So i think the steps would be:

1. Look through the code during build time and find any fields marked with the Attribute [DiLogger].
2. Automatically generate the constructor (or update it) to add an ILogger parameter if needed.
3. Make sure the logger gets assigned to the field.

Possible solution:

```csharp
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[DiLogger]
private readonly ILogger _logger;

private readonly IWeatherService _weatherService;

public WeatherForecastController(IWeatherService weatherService)
{
_weatherService = weatherService;
}

[HttpGet]
public IEnumerable Get()
{
_logger.LogInformation("Fetching weather forecast");
return _weatherService.GetForecast();
}
}
```

Problems: Not breaking the existing Di container and its infrastructure.

### Additional context

I’ve also seen some codebases use a base class approach where the base controller has a logger, and child controllers reuse that. That works, but it still adds some complexity with inheritance, and you still need to inject the logger into the base class. I thought an attribute-based option might keep things simpler and more flexible.

Let me know your thoughts.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.