NET Core MVC的Spring Boot Autowired注释等效

Bos*_*anT 6 c# dependency-injection autowired asp.net-core-mvc

问题提到了这一切。

在春季启动中,我能够使用AutoWired注释自动将依赖项注入控制器。

class SomeController extends Controller {
    @AutoWired
    private SomeDependency someDependency;
}
Run Code Online (Sandbox Code Playgroud)

对于我很好奇它是否具有此批注,当前的实现方式是将其作为参数添加到构造函数中

[Route("api/[controller]")]
public class SomeController : Controller
{
    private SomeContext _someContext;

    public SomeController(SomeContext someContext)
    {
        _someContext = someContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

没有注释。

您只需要确保在DI容器的组合根目录(通常是 Startup.ConfigureServices

public void ConfigureServices(IServiceCollection services) {

    //...

    services.AddScoped<SomeContext>();

    //...
}
Run Code Online (Sandbox Code Playgroud)

如果您的情况SomeContextDbContext派生类,则将其注册为此类

var connection = @"some connection string";
services.AddDbContext<SomeContext>(options => options.UseSqlServer(connection));
Run Code Online (Sandbox Code Playgroud)

在解析控制器时,框架将解析已知的显式依赖项并将其注入。

参考依赖注入在ASP.NET核心

引用依赖注入到控制器中