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>
相关推荐
世界哪有真情15 分钟前
拿人类意识卡 AI?等于用 bug 验收正式产品
前端·人工智能·后端
Csvn3 小时前
Day 3:LIKE 与模式匹配 — 让查询学会"模糊搜索"
后端·sql
Hazenix4 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦4 小时前
GO_复合类型---指针
开发语言·后端·golang
IT_陈寒4 小时前
SpringBoot自动装配坑了我一天,原来问题出在这
前端·人工智能·后端
星栈5 小时前
深度复盘:比 EventLoop 更隐蔽!Node 微任务堆积引发的线上接口雪崩事故
后端·node.js
名字还没想好☜5 小时前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice
诸神缄默不语5 小时前
FastAPI后端配置CORS中间件支持浏览器跨域访问
后端·fastapi
Fanta丶5 小时前
14.Activiti7 网关 排他网关ExclusiveGateway、并行网关ParallelGateway
后端
明月_清风5 小时前
robots.txt 完全指南:从入门到精通
后端·爬虫