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>
相关推荐
didiplus7 小时前
Python 入门第一课:为什么选择 Python?3 分钟搭建你的第一个程序
后端
dreamxian7 小时前
苍穹外卖day11
java·spring boot·后端·spring·mybatis
华科易迅8 小时前
Spring装配对象方法-注解
java·后端·spring
AwesomeDevin9 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
Victor3569 小时前
MongoDB(60)如何使用explain命令?
后端
Victor35610 小时前
MongoDB(59)如何分析查询性能?
后端
怒放吧德德12 小时前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端
后端不背锅12 小时前
可观测性体系:日志、指标、链路追踪
后端
苍何12 小时前
把小度音箱接入小龙虾是一种什么体验?
后端