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>
相关推荐
KYGALYX几秒前
服务异步通信
开发语言·后端·微服务·ruby
掘了6 分钟前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法42 分钟前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment1 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte2 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行3 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple3 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东3 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble3 小时前
springboot的核心实现机制原理
java·spring boot·后端
全栈老石4 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python