-1

So I'm trying to create a Web API using .NET 5.0 and cannot get my head around how should i inject my dependency.

In a course that I follow the instructor uses an interface for one dependency and a class for another. So to figure out the difference between these usages I tried to code the same dependency in a class and then in an interface.

This is the interface one; enter image description here

This is class one;

enter image description here

And they work exactly the same. So what is the difference? Are there any advantages to using one over another? Which one should I use in which case? Thank you so much.

Shibu
  • 102
  • 9
hakanAkdogan
  • 223
  • 2
  • 3
  • 10
  • 2
    Much easier to mock, is probably one reason – Charlieface Jul 31 '22 at 15:48
  • 1
    Does this answer your question? [Interfaces — What's the point?](https://stackoverflow.com/questions/6802573/interfaces-whats-the-point) – Progman Jul 31 '22 at 16:00
  • I mean, i was wondering if DI has any advantages or disadvantages with classes or interfaces. Thank you tho. – hakanAkdogan Jul 31 '22 at 16:03
  • 1
    Using interfaces, abstractions and other modern design methods allows you to create thousands of lines of code out of the blue. Thanks to this, you will look like an effective employee in the eyes of the employer. It's just a joke, but... – Alexander Petrov Jul 31 '22 at 16:23

1 Answers1

3

Just inject IItemRepository in any place you need and you can easily replace your implementation in future if you want only in one place (just like that: services.AddSingleton<IItemRepository, SqlServerRepository> or something like this). And, of course, you can easily write unit tests with it.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Elvis
  • 108
  • 1
  • 7
  • Thank you, so much! So if I create a service that i won't change in the future and has just one job, should i use a class for it or stick with the interface? – hakanAkdogan Jul 31 '22 at 16:00
  • 1
    Anyway, you should use interface, cause you cannot absolutely know about future decisions. And, definitely, this is an indicator of good code :) – Elvis Jul 31 '22 at 16:10