gpt4 book ai didi

c# - Asp.net MVC 样板依赖注入(inject)不起作用

转载 作者:太空狗 更新时间:2023-10-29 21:26:43 25 4
gpt4 key购买 nike

我正在玩 Asp.Net MVC 6 boilerplate项目。我正在尝试为我的一项服务配置依赖项注入(inject)。内置的 IoC 容器似乎忽略了我的绑定(bind)。

启动.cs

public void ConfigureServices(IServiceCollection services){
/*boilerplate's default bindings*/
services.AddTransient<IDummy, Dummy>(p => new Dummy()
{
name = "from injection"
});
}

HomeController.cs

public IActionResult Index(IDummy dummy){
var test = dummy.name;
return this.View(HomeControllerAction.Index);
}

异常(exception):

ArgumentException: Type 'Presentation.WebUI.Controllers.IDummy' does not have a default constructor

你能告诉我我做错了什么吗?

最佳答案

该异常是因为框架无法将操作参数绑定(bind)到接口(interface)。

当框架默认使用构造函数注入(inject)时,您正在尝试对 Action 进行注入(inject)。

引用:Dependency Injection and Controllers

Constructor Injection

ASP.NET Core’s built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container.

public class HomeController : Controller {
IDummy dummy;
public HomeController(IDummy dummy) {
this.dummy = dummy
}

public IActionResult Index(){
var test = dummy.name;
return this.View(HomeControllerAction.Index);
}
}

ASP.NET Core MVC controllers should request their dependencies explicitly via their constructors. In some instances, individual controller actions may require a service, and it may not make sense to request at the controller level. In this case, you can also choose to inject a service as a parameter on the action method.

Action Injection with FromServices

Sometimes you don’t need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices] as shown here:

public IActionResult Index([FromServices] IDummy dummy) {
var test = dummy.name;
return this.View(HomeControllerAction.Index);
}

关于c# - Asp.net MVC 样板依赖注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com