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

Spring boot Autowired annotation equivalent for .net core mvc

问题都提到了。

在 spring 引导中,我可以使用 AutoWired 注释 自动 将依赖项注入我的控制器。

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

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

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

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

没有注释。

您只需要确保在通常为 Startup.ConfigureServices

的组合根目录中向 DI 容器注册依赖项
public void ConfigureServices(IServiceCollection services) {

    //...

    services.AddScoped<SomeContext>();

    //...
}

如果在您的情况下 SomeContextDbContext 派生的 class 那么就这样注册它

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

解析控制器时,框架将解析已知 explicit dependencies 并注入它们。

引用Dependency Injection in ASP.NET Core

引用Dependency injection into controllers

可以使用NAutowired,字段注入

开箱即用,Microsoft.Extensions.DependencyInjection 不提供 属性 setter 注入(仅构造函数注入)。但是,您可以使用 Quickwire NuGet 包来实现这一点,它会为您完成所有必要的管道。它扩展了 ASP.NET 核心内置依赖注入容器以允许使用属性注册服务。

要使用它,首先将这两行添加到您的 ConfigureServices 方法中:

public void ConfigureServices(IServiceCollection services)
{
    // Activate controllers using the dependency injection container
    services.AddControllers().AddControllersAsServices();
    // Detect services declared using the [RegisterService] attribute
    services.ScanCurrentAssembly();

    // Register other services...
}

然后简单地用 [RegisterService] 属性装饰你的控制器,并用 [InjectService]:

装饰任何 属性 以自动装配
[Route("api/[controller]")]
[RegisterService(ServiceLifetime.Transient)]
public class SomeController : Controller
{
    [InjectService]
    private SomeContext SomeContext { get; init; }
}

现在 SomeContext 自动 注入相应的注册服务,而无需通过构造器歌舞。

有关详细信息,您还可以查看 this table 映射出哪个 Quickwire 属性对应于哪个 Spring 引导注释。