Out of the box, Microsoft.Extensions.DependencyInjection
doesn't provide property setter injection (only constructor injection). However, you can achieve this by using the Quickwire NuGet package, which does all the necessary plumbing for you. It extends the ASP.NET core built-in dependency injection container to allow service registration using attributes.
To use it, first add these two lines to your ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
// Activate controllers using the dependency injection container
services.AddControllers().AddControllersAsServices();
// Detect services declared using the [RegisterService] attribute
services.ScanCurrentAssembly();
// Register other services...
}
Then simply decorate your controller with the [RegisterService]
attribute, and decorate any property to autowire with [InjectService]
:
[Route("api/[controller]")]
[RegisterService(ServiceLifetime.Transient)]
public class SomeController : Controller
{
[InjectService]
private SomeContext SomeContext { get; init; }
}
Now SomeContext
will automagically get injected with the corresponding registered service without having to go through the constructor song and dance.
For more information, you can also check out this table that maps out which Quickwire attribute corresponds to which Spring Boot annotation.