Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot Autowired annotation equivalent for .net core mvc

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;
    }
}
like image 777
BossmanT Avatar asked Jan 22 '18 17:01

BossmanT


People also ask

What is Autowired annotation in Spring MVC?

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.

What can I use instead of Autowired?

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.

What is difference between @autowired and @resource in Spring?

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.

What is difference between @autowired and @inject?

@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.


2 Answers

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

like image 170
Nkosi Avatar answered Oct 09 '22 19:10

Nkosi


You can use NAutowired,the field injection

like image 3
FatTiger Avatar answered Oct 09 '22 19:10

FatTiger