ASP.NET MVC-构建服务层+注入服务

环境:

win10, .NET 6.0,IIS


目录

问题描述

ASP.NET MVC 项目中,将业务逻辑从控制器(Controller)中拆分到**服务层(Service Layer)**是一种常见的架构设计模式。这种设计模式可以提高代码的可维护性、可测试性和可复用性。

现在假设我需要将控制器中酶相关的逻辑放到服务层,以期尽可能降低控制器的长度和复杂度。

实现效果

假设服务层有一个函数是GetMsg()(返回一个字符串,内容为"EnzymesService.GetMsg()"),控制器会在Index()中调用,并将返回的结果显示到Index.cshtml中。实现效果:

调用成功。

实现

下面的实现只给出部分代码,剩余请自行补足。

项目结构

shell 复制代码
/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。

实现服务层

csharp 复制代码
// IEnzymesService.cs
/// <summary>
/// 定义与酶相关的服务接口
/// </summary>
public interface IEnzymesService {
	string GetMsg();
}

// EnzymesService.cs
public class EnzymesService : IEnzymesService {
	public string GetMsg() { 
		return "EnzymesService.GetMsg()";
	}
}

配置Unity

找到UnityConfig.cs

修改:

csharp 复制代码
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(),增加:

csharp 复制代码
// 配置依赖注入
UnityConfig.RegisterComponents();

注入服务

修改控制器:

csharp 复制代码
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();
    }
	
	// ...
}

修改视图

增加:

html 复制代码
<h2>@ViewBag.Message</h2>
相关推荐
PanZonghui8 分钟前
Centos项目部署之安装数据库MySQL8
linux·后端·mysql
Victor35611 分钟前
MySQL(119)如何加密存储敏感数据?
后端
用户39661446871922 分钟前
TypeScript 系统入门到项目实战-慕课网
后端
guojl27 分钟前
Dubbo SPI原理与设计精要
后端
Lemon程序馆29 分钟前
搞懂 GO 的垃圾回收机制
后端·go
用户81221993672239 分钟前
React18+Next.js14+Nest.js全栈开发复杂低代码项目-仿问卷星
后端
喜欢吃豆43 分钟前
目前最火的agent方向-A2A快速实战构建(二): AutoGen模型集成指南:从OpenAI到本地部署的全场景LLM解决方案
后端·python·深度学习·flask·大模型
寻月隐君1 小时前
Rust 网络编程实战:用 Tokio 手写一个迷你 TCP 反向代理 (minginx)
后端·rust·github
汪子熙1 小时前
理解 git checkout 与 git reset 的联系和区别
后端