Home > Software engineering >  What's the advantage of using interfaces over classes (if there are any) while using dependency
What's the advantage of using interfaces over classes (if there are any) while using dependency

Time:08-01

I'm trying to create an ASP.NET Core 5 Web API and cannot get my head around about 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 among these usages, I tried to code the same dependency in a class and then in a interface.

This is the interface one:

enter image description here

This is the class one:

enter image description here

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

CodePudding user response:

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.

  • Related