环境:
win10, .NET 6.0,IIS
问题描述
在 ASP.NET MVC 项目中,将业务逻辑从控制器(Controller)中拆分到**服务层(Service Layer)**是一种常见的架构设计模式。这种设计模式可以提高代码的可维护性、可测试性和可复用性。
现在假设我需要将控制器中酶相关的逻辑放到服务层,以期尽可能降低控制器的长度和复杂度。
实现效果
假设服务层有一个函数是GetMsg()
(返回一个字符串,内容为"EnzymesService.GetMsg()"
),控制器会在Index()
中调用,并将返回的结果显示到Index.cshtml
中。实现效果:
调用成功。
实现
下面的实现只给出部分代码,剩余请自行补足。
项目结构
/Controllers
HomeController.cs
/Services
EnzymesService.cs
IEnzymesService.cs
/Models
Enzymes.cs
/Views
/Home
Index.cshtml
安装Unity.Mvc
在 ASP.NET MVC 中,通常使用 Unity、Autofac 或 Ninject 等依赖注入容器。
我选择用NuGet安装Unity.Mvc。
实现服务层
// IEnzymesService.cs
/// <summary>
/// 定义与酶相关的服务接口
/// </summary>
public interface IEnzymesService {
string GetMsg();
}
// EnzymesService.cs
public class EnzymesService : IEnzymesService {
public string GetMsg() {
return "EnzymesService.GetMsg()";
}
}
配置Unity
找到UnityConfig.cs
修改:
public static class UnityConfig {
// ...
public static void RegisterComponents()
{
var container = new UnityContainer();
// 注册服务
container.RegisterType<IEnzymesService, EnzymesService>();
// 将容器设置为 MVC 的默认依赖解析器
System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
修改Global.asax
修改Application_Start()
,增加:
// 配置依赖注入
UnityConfig.RegisterComponents();
注入服务
修改控制器:
public class HomeController : Controller
{
private readonly EnzymesService enzymesService;
/// <summary>
/// 通过构造函数注入依赖
/// </summary>
/// <param name="enzymesService"></param>
public HomeController(EnzymesService enzymesService)
{
this.enzymesService = enzymesService;
}
public ActionResult Index()
{
// 调用服务
var msg = enzymesService.GetMsg();
ViewBag.Message = msg;
return View();
}
// ...
}
修改视图
增加:
<h2>@ViewBag.Message</h2>