加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Asp.net MVC样板依赖注入不起作用

发布时间:2020-12-15 08:38:26 所属栏目:百科 来源:网络整理
导读:我正在玩 Asp.Net MVC 6 boilerplate项目.我正在尝试为我的一个服务配置依赖注入.看起来内置的IoC容器忽略了我的绑定. Startup.cs public void ConfigureServices(IServiceCollection services){ /*boilerplate's default bindings*/ services.AddTransientI
我正在玩 Asp.Net MVC 6 boilerplate项目.我正在尝试为我的一个服务配置依赖注入.看起来内置的IoC容器忽略了我的绑定.

Startup.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);
}

例外:

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

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

解决方法

该异常是因为框架无法将操作参数绑定到接口.

当框架默认使用构造函数注入时,您正尝试对Action执行注入.

参考: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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读