简体   繁体   中英

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.

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. Since it is broad concept,I can not explain everything here(try to search on web)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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