简体   繁体   English

传递Controller构造函数中的接口或类以进行依赖项注入

[英]Pass Interface or Class in Controller Constructor for dependency injection

My controller look like bellow. 我的控制器看起来像波纹管。 But I do not know when to pass interface and when to pass class at constructor. 但是我不知道何时传递接口,何时传递构造函数中的类。 Or does it really matter? 还是真的重要吗? I search but do not get answer. 我搜索但没有得到答案。

public class MyController
    {
      private readonly IMyService _myService;
      public MyController(IMyService myService)
      {
        _myService=myService;
      }
    }

OR 要么

public class MyController
    {
      private readonly IMyService _myService;
      public MyController(MyService myService)
      {
        _myService=myService;
      }
    }

And my dependency injection like 我的依赖注入就像

    builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();
public class MyController
    {
      private readonly IMyService _myService;
      public MyController(IMyService myService)
      {
        _myService=myService;
      }
    }

is better since it allows you to implement IMyService differently without having to touch MyController. 更好,因为它允许您以其他方式实现IMyService,而无需接触MyController。

You always need to pass interface in you constructor(your first implementation). 您始终需要在构造函数中传递接口(您的第一个实现)。 If you will pass classes in constructor then there is no benefit of dependency injection because you are already telling your constructor which class is implementing this interface and this code line 如果您将在构造函数中传递类,那么依赖注入没有任何好处,因为您已经在告诉构造函数哪个类正在实现此接口和此代码行

 builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();

will be useless.Dependency injection is something which is used to bind your interface and its implementation at run time and not compile time. 依赖注入是一种用于在运行时而不是编译时绑定接口及其实现的东西。

PS: Always use your first implementation. PS:始终使用第一个实现。 Since it is broad concept,I can not explain everything here(try to search on web) 由于是广义概念,因此我无法在此处解释所有内容(尝试在网络上搜索)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM