c# - .net core mvc 的 Spring boot Autowired 注释等价物

标签 c# dependency-injection asp.net-core-mvc autowired

问题说明了一切。

在 spring boot 中,我可以使用 AutoWired 注释自动将依赖项注入(inject)我的 Controller 。

class SomeController extends Controller {
    @AutoWired
    private SomeDependency someDependency;
}

对于 我很好奇它是否有这个注解,目前的方法是将它作为参数添加到构造函数中

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

    public SomeController(SomeContext someContext)
    {
        _someContext = someContext;
    }
}

最佳答案

没有注释。

您只需要确保在组合根目录下向 DI 容器注册依赖项,通常是 Startup.ConfigureServices

public void ConfigureServices(IServiceCollection services) {

    //...

    services.AddScoped<SomeContext>();

    //...
}

如果在你的情况下 SomeContext 是一个 DbContext 派生类,那么就这样注册它

var connection = @"some connection string";
services.AddDbContext<SomeContext>(options => options.UseSqlServer(connection));

当解析 Controller 时,框架将解析已知的 explicit dependencies并注入(inject)它们。

引用 Dependency Injection in ASP.NET Core

引用 Dependency injection into controllers

关于c# - .net core mvc 的 Spring boot Autowired 注释等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387157/

相关文章:

c# - ASP.NET Core OnModelCreating 强制触发每个请求

C#,比较两种不同类型的列表

c# - 日期时间 : how to display as DD. MM.YYYY?

java - Spring Boot 中的策略

javascript - Ember : How do I inject into a view?

c# - 如何对数据库中的用户使用 Windows 身份验证

c# - 使用匿名对象创建列表

c# - 1/252 = 0 在 C# 中?

javascript - 在 JavaScript 中实现 C# 的使用

c# - 如何在 asp.net core 中从 JWT 检索 ClaimsPrincipal