Spring boot Autowired annotation equivalent for .net core mvc
You can use NAutowired,the field injection
There is no annotation.
You just need to make sure you register the dependency with the DI container at the composition root which is usually Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services) {
//...
services.AddScoped<SomeContext>();
//...
}
If in your case SomeContext
is a DbContext
derived class then register it as such
var connection = @"some connection string";
services.AddDbContext<SomeContext>(options => options.UseSqlServer(connection));
When resolving the controller the framework will resolve known explicit dependencies and inject them.
Reference Dependency Injection in ASP.NET Core
Reference Dependency injection into controllers
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.