2

I am working with ASP.NET MVC5 project. I am new to commercial programming and I am a little bit confused about Interfeaces, I haven't use them before. I have project which is almost done.

Here is an example:

public interface IUserService()
{
   bool ValidateUser(string name, string password);
   //.. others
}

I have also class implmenting this service

public class UserService : IUserService
{
   public bool ValidateUser(string name, string password)
   {
     //code
   }
   //.. others
}

I am using UserService if my Controllers as example:

public class HomeController : Controller
{
   IUserService _userService;

   public HomeController(IUserService userService)
   {
     _userService = userService;
   }

   [HttpGet]
   JsonResult Anymethod(string name, string pw)
   {
     return Json(_userService.ValidateUser(name,pw), JsonRequestBeh.AllowGet);
  }
} 

Why instead of IUserService not use UserService as static class without implementing IUserService?

public static UserService
{
   ValidateUser(string user, string pw)
   {
     //code
   }
}

What are beneift of using interfaces if it is in that case similar?

mason
  • 31,774
  • 10
  • 77
  • 121
miechooy
  • 3,178
  • 12
  • 34
  • 59
  • The use of an interface in this case follows the dependency injection design pattern. This pattern is very useful when you want to do unit tests with mocking. – Gabriel Feb 25 '16 at 22:21
  • I'm guessing you haven't done a lot of unit tests if you're not familiar with interfaces. Two recommendations: start doing unit tests, and watch [this video](https://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DEV-B412#fbid=). – mason Feb 25 '16 at 22:24

2 Answers2

1

Idea is not to have dependency in your controller on real implementation of your service. If you are injecting service through interface you are controlling implementation outside of controller. Basic reasoning for this is to make testing of your controller easier. You can inject mocked service when testing controller logic. Check dependency injection pattern.

Kreso Jurisic
  • 100
  • 2
  • 9
-1

Because of Polymorphism.

This post might be useful to you.

Community
  • 1
  • 1
brandon-irl
  • 115
  • 1
  • 9