Asp.net core mvc 用于.net核心mvc的Spring boot自动连线注释等效项

Asp.net core mvc 用于.net核心mvc的Spring boot自动连线注释等效项,asp.net-core-mvc,c#,dependency-injection,autowired,Asp.net Core Mvc,C#,Dependency Injection,Autowired,问题提到了这一切 在spring boot中,我能够使用自动连线注释自动向控制器中注入依赖项 class SomeController extends Controller { @AutoWired private SomeDependency someDependency; } 因为我很好奇它是否有这个注释,目前的方法是将它作为参数添加到构造函数中 [Route("api/[controller]")] public class SomeController : Contro

问题提到了这一切

在spring boot中,我能够使用
自动连线
注释自动向控制器中注入依赖项

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>();

    //...
}
在解析控制器时,框架将解析已知的控制器并注入它们

参考文献


参考

您可以使用,字段注入

默认的DI容器基本上只允许构造函数注入,因此所有依赖项都应设置为构造函数参数。@juunas该评论是针对我还是OP的?对您的答案的一个改进建议:)因为
@Autowired
在Spring中进行属性注入,提到差异可能很重要。@juunas这就是我要求确认的原因。您的声明并不完全准确,因为它(框架)也允许操作注入。检查第二个链接。我没有特别提到构造函数注入,因为它不是唯一可用的选项。
var connection = @"some connection string";
services.AddDbContext<SomeContext>(options => options.UseSqlServer(connection));