我正在使用 ASP.NET MVC5 项目。我是商业编程的新手,我对 Interfeaces 有点困惑,我以前没有使用过它们。我的项目快完成了。
这是一个例子:
public interface IUserService()
{
bool ValidateUser(string name, string password);
//.. others
}
我也有实现这项服务的类(class)
public class UserService : IUserService
{
public bool ValidateUser(string name, string password)
{
//code
}
//.. others
}
以我的 Controller 为例,我正在使用 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
}
}
如果在那种情况下相似,使用接口(interface)有什么好处?
最佳答案
想法是不要让 Controller 依赖于服务的实际实现。如果您通过接口(interface)注入(inject)服务,则您正在控制 Controller 外部的实现。这样做的基本原因是为了让您的 Controller 测试更容易。您可以在测试 Controller 逻辑时注入(inject)模拟服务。检查依赖注入(inject)模式。
关于c# - ASP C# 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35639368/