在.net core中,你注册你的服务,然后把它注入到你想要的控制器中,现在如果我必须在我的控制器中注入3个服务或让我们说n个服务,我应该在我的构造函数中传递n个参数,但它是否太多?
这是我的控制器。
public class AcessInfoController : ControllerBase
{
// private DbContextClass db;
private IAccessInfo _acess;
public AcessInfoController(IAccessInfo access)
{
_acess = access;
// db = context;
}
现在我需要注入另一个IAnotherInterface,什么是最好的做法,使它更可读?
我认为这与最佳实践无关......
如果你有多个服务做不同的事情,你需要他们在一个控制器中注入的方式是如下。
public class AcessInfoController : ControllerBase
{
private IAccessInfo _access;
private IAnotherInterface _another;
private IAndAnotherInterface _andAnother;
public AcessInfoController(IAccessInfo access, IAnotherInterface another, IAndAnotherInterface andAnother)
{
_access = access;
_another = another;
_andAnother = andAnother;
}
当然,你的 ctor
-行可能有点长,但这不是问题。
有什么办法呢?你可以把你的三个接口包在第四个接口里。但是为什么呢?