Question mentions it all.
In spring boot I am able to use the AutoWired
annotation to automagically inject a dependency into my controller.
class SomeController extends Controller {
@AutoWired
private SomeDependency someDependency;
}
For asp.net-core-mvc I am curious as to if it has this annotation, currently the way to do it is by adding it as an argument to the constructor
[Route("api/[controller]")]
public class SomeController : Controller
{
private SomeContext _someContext;
public SomeController(SomeContext someContext)
{
_someContext = someContext;
}
}
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
Multiple classes which fit the @Autowired bill You can indicate a @Primary candidate for @Autowired. This sets a default class to be wired. Some other alternatives are to use @Resource, @Qualifier or @Inject.
The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application.
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
You can use NAutowired,the field injection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With