简体   繁体   English

如果我使用依赖注入,如何在 web API Controller 构造函数中传递多个接口参数?

[英]How to pass multiple interface parameters in a web API Controller contructor if I am using Dependency Injection?

I'm using dependency Injection to call my objects, so is there a neater way of adding more parameters in the constructor without making the constuctor signature long just like my case below?我正在使用依赖注入来调用我的对象,那么有没有一种更简洁的方法可以在构造函数中添加更多参数,而不会像下面的情况一样使构造函数签名变长?

   public ObjectController(IParam1 param1, IParam2 param2, IParam3 param3, 
   IParam4 param4,IParam5 param6,IParam7 param8)
    {
        _param1= param1;
        _param2 = param2;
        _param3= param3;
        _param4= param4;
        _param5= param5;
        _param6= param6;
        _param7= param7;
        _param8= param8;
    }

As the others have said, your controller has too much responsibility.正如其他人所说,您的 controller 责任太大。 I would recommend you break your functionality into Services/Business Logic services.我建议您将功能分解为服务/业务逻辑服务。

public class UserService : IUserService {
    
    IParam _param;
    IParam2 _param2;
    
    public UserService(IParam param, IParam2 param2) {
        _param = param;
        _param2 = param2;
    }
}


public class LoginService : ILoginService {
    
    IParam _param;
    IParam2 _param2;
    
    public UserService(IParam param, IParam2 param2) {
        _param = param;
        _param2 = param2;
    }
}

Then you can inject it into your controller然后你可以将它注入你的 controller

public Controller(IUserService userService, ILoginService loginService) { ... }

And if it it still too much I would recommend spliting your controller as well.如果它仍然太多,我建议也拆分你的 controller。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过依赖注入传递Web API请求? - How would I pass a Web API Request through Dependency Injection? 传递Controller构造函数中的接口或类以进行依赖项注入 - Pass Interface or Class in Controller Constructor for dependency injection 使用依赖注入在 controller 中注入接口的 IEnumerable - Inject an IEnumerable of interface in controller using Dependency Injection Autofac - 依赖注入MVC​​控制器和Web Api控制器 - Autofac - dependency injection for MVC controller and Web Api controller 如何将多个参数传递给控制器​​? - How do I pass in multiple parameters to a controller? 我应该如何通过Autofac.Dependency注入库将参数传递给Autofac容器以实现自动依赖关系解析 - How should I pass parameters to the Autofac container for auto dependency resolution via Autofac.Dependency injection lib Web Api和依赖注入 - Web Api and Dependency Injection C#(Web API)依赖项注入(带有Unity)返回类型接口 - C# (Web API) dependency injection (with Unity) return type Interface 构造函数的依赖注入参数 - Dependency Injection pass parameters by constructor 在ASP.NET Core Web API中使用依赖项注入时未调用Controller Action方法 - Controller Action method not called while using dependency injection in asp.net core web api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM