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)
对于asp.net-core-mvc,我很好奇它是否具有此批注,当前的实现方式是将其作为参数添加到构造函数中
[Route("api/[controller]")]
public class SomeController : Controller
{
private SomeContext _someContext;
public SomeController(SomeContext someContext)
{
_someContext = someContext;
}
}
Run Code Online (Sandbox Code Playgroud)
没有注释。
您只需要确保在DI容器的组合根目录(通常是 Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services) {
//...
services.AddScoped<SomeContext>();
//...
}
Run Code Online (Sandbox Code Playgroud)
如果您的情况SomeContext是DbContext派生类,则将其注册为此类
var connection = @"some connection string";
services.AddDbContext<SomeContext>(options => options.UseSqlServer(connection));
Run Code Online (Sandbox Code Playgroud)
在解析控制器时,框架将解析已知的显式依赖项并将其注入。