ASP C#接口

时间:2016-02-25 22:08:49

标签: c# asp.net-mvc dependency-injection interface static-class

我正在使用ASP.NET MVC5项目。我是商业编程的新手,我对Interfeaces有点困惑,我以前没有使用它们。我的项目差不多完成了。

以下是一个例子:

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

我也有课程实现这项服务

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

如果我的控制器为例,我正在使用UserService:

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);
  }
} 

为什么而不是IUserService而不使用UserService作为静态类而不实现IUserService?

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

如果在这种情况下使用接口有什么好处呢?

2 个答案:

答案 0 :(得分:1)

理念不是在控制器上依赖于服务的实际实现。如果您通过接口注入服务,则控制控制器之外的实现。对此的基本推理是使控制器的测试更容易。您可以在测试控制器逻辑时注入模拟服务。检查依赖注入模式。

答案 1 :(得分:-1)

由于Polymorphism

This帖子可能对您有用。