asp.net core mvc 之 依赖注入

一、视图中使用依赖注入

1、core目录下添加 LogHelperService.cs 类

复制代码
    public class LogHelperService
    {
        public void Add()
        {

        }
        public string Read()
        {
            return "日志读取";
        }
    }

2、Startup.cs 文件中 注入依赖注入

3、Views目录中 _ViewImports.cshtml 添加引用

4、视图使用

二、控制器使用依赖注入

1、Startup.cs 文件中 注入依赖注入

2、控制器中使用

cs 复制代码
public class HomeController : BaseController
{

        //通过一个字段来存储
        LogHelperService logHelperService;

        public HomeController(LogHelperService loghelperservice)
        {
            this.logHelperService = loghelperservice;
            logHelperService.Add();
        }
}

三、接口方式接收依赖对象

1、提取接口

cs 复制代码
    public interface ILogHelperService
    {
        void Add();
        string Read();
    }

2、Startup.cs 文件中 注入依赖注入

services.AddTransient<ILogHelperService, LogHelperService>();

3、控制器使用

cs 复制代码
public class HomeController : BaseController
{

        //通过一个字段来存储
        ILogHelperService ilogHelperService;

        public HomeController(ILogHelperService iloghelperservice)
        {
            this.ilogHelperService = iloghelperservice;
            ilogHelperService.Add();
        }
}

四、Action注入依赖对象

1、Startup.cs 文件中 注入依赖注入

2、Action代码

cs 复制代码
//[FromServices] 这个标注 告诉MVC 这个参数不用用户传递过来的get post方式。
//而是依赖容器传递过来的
//还可以接收传递过来的值
public IActionResult Contact([FromServices] ILogHelperService loghelper)
{
    return Content(loghelper.Read());
            
}
相关推荐
sakiko_2 天前
Swift学习笔记34-MVC架构,SwiftUI与UIkit混编练习
笔记·学习·swiftui·mvc·swift
止水编程 water_proof3 天前
Spring Web MVC 入门
前端·spring·mvc
Mahir085 天前
Spring MVC 深度解密:从 DispatcherServlet 到请求处理全流程
java·后端·spring·面试·mvc
辰海Coding7 天前
MiniSpring框架学习-整合 IoC 和 MVC(NPC)
学习·spring·mvc
辰海Coding7 天前
MiniSpring框架学习-为什么一个请求访问 /helloworld,最后能调用到某个 Controller 方法?原始 MVC实现
java·学习·程序人生·spring·mvc
那个失眠的夜13 天前
SpringBoot
java·开发语言·spring boot·spring·mvc·mybatis
cheems952714 天前
[Spring MVC] 统一功能与拦截器实践总结
java·spring·mvc
William_cl14 天前
第 1 节:MVC + DataTable 百万数据秒加载 —— 企业级服务端分页实战
mvc·状态模式
ze^015 天前
Day01 Web应用&架构搭建&域名源码&站库分离&MVC模型&解析受限&对应路径
安全·web安全·架构·mvc·安全架构
身如柳絮随风扬15 天前
MVC 三层结构深度解析:概念、作用与实战经验
mvc