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>
相关推荐
xyy1232 分钟前
SixLabors.ImageSharp 使用指南
后端
阑梦清川1 小时前
docker部署tomcat和nginx
后端
程序员码歌1 小时前
豆包Seedream4.0深度体验:p图美化与文生图创作
android·前端·后端
风雨同舟的代码笔记2 小时前
AI上下文工程:智能体系统的核心竞争力——超越Prompt Engineering的新范式
后端
程序新视界2 小时前
什么是MySQL JOIN查询的驱动表和被驱动表?
数据库·后端·mysql
无限进步_3 小时前
C语言文件操作全面解析:从基础概念到高级应用
c语言·开发语言·c++·后端·visual studio
咖啡教室3 小时前
每日一个计算机小知识:IP和域名
后端
咖啡教室3 小时前
每日一个计算机小知识:Host
后端