.Net利用Microsoft.Extensions.DependencyInjection配置依赖注入

一、概述

为了让接口程序更加模块化和可测试,采用依赖注入的方式调用接口方法。

二、安装Microsoft.Extensions.DependencyInjection

在NuGet里面搜索Microsoft.Extensions.DependencyInjection,并进行安装。

三、代码编写

3.1 创建Service 实现类
csharp 复制代码
/*************************************
*  功    能:测试Service实现类
*  创 建 人:********
*  创建时间:2024-02-19
* ***********************************/
namespace Application
{
    /// <summary>
    /// 测试Service.
    /// </summary>
    public class TestService : ITestService
    {
        /// <summary>
        /// 测试查询.
        /// </summary>
        public List<AgentGroup> TestSelect()
        {
             var list =   SqlSugarORM.SqlSugarHelper.Db.Queryable<AgentGroup>().ToList();
             return list;
        }

    
    }
}
3.2 创建Service 声明类
csharp 复制代码
/*************************************
*  功    能:测试Service 接口类声明类
*  创 建 人:********
*  创建时间:2024-02-19
* ***********************************/

namespace CadApplication.Service
{

    public interface ITestService
    {
        /// <summary>
        /// 测试查询.
        /// </summary>
        List<AgentGroup> TestSelect();

    }
}
3.3 控制器里面通过构造函数注入
csharp 复制代码
/*************************************
 *  功    能:测试控制器
 *  创 建 人:********
 *  创建时间:2024-02-19
 * ***********************************/
namespace WebApi.Controllers
{

    /// <summary>
    /// 测试Controller.
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        private readonly ITestService _testService;
        /// <summary>
        /// 构造函数.
        /// </summary>
        /// <param name="testService"></param>
        public TestController(ITestService testService) 
        {
            _testService=testService;

        }

        /// <summary>
        /// 测试查询.
        /// </summary>
        [Route("TestSelect")]
        [HttpPost]
        public List<AgentGroup> TestSelect() 
        {
            return _testService.TestSelect();
        }
    }
}
3.4 在启动类里面配置注入的Service
csharp 复制代码
builder.Services.AddSingleton<ITestService, TestService>();

整体的Program.cs代码如下:

csharp 复制代码
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ITestService, TestService>().AddSingleton<DrawLineService>();



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();


app.Run();
3.5 如果需要在某一个类里面单独调用也可以这样写
csharp 复制代码
 static void Main(string[] args)  
    {  
        // 配置依赖注入容器  
        var serviceCollection = new ServiceCollection();  
        serviceCollection.AddTransient<IGreetingService, GreetingService>(); // 注册服务及其实现  
  
        var serviceProvider = serviceCollection.BuildServiceProvider(); // 构建服务提供者  
  
        // 解析依赖项并使用  
        var greetingService = serviceProvider.GetService<IGreetingService>();  
        Console.WriteLine(greetingService.GetGreeting());  
    }  

四、结束

至此.net配置依赖注入结束。

相关推荐
Data-Miner3 天前
大语言模型+智能体AI,122页PPT详解落地应用培训!
人工智能·microsoft·语言模型
2601_962072553 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
c++之路3 天前
备忘录模式(Memento Pattern)
c++·microsoft
Solis程序员3 天前
MCP (Model Context Protocol):AI应用连接外部世界的标准协议
人工智能·microsoft·agent·skill·mcp
诺未科技_NovaTech3 天前
上海诺未携手惠灵顿中国,基于微软 Azure 打造 AI 教育生态标杆
人工智能·microsoft·azure·ai教育
hnult3 天前
在线笔试平台如何选型?考试云九重防作弊 + 六大 AI 能力 智能招聘笔试解决方案
人工智能·笔记·microsoft·信息可视化·课程设计
步步为营DotNet3 天前
Blazor 与 Microsoft.Extensions.AI 在客户端性能优化中的协同应用
人工智能·microsoft·性能优化
hai3152475434 天前
九章编程法 · 猜数字游戏 (GW-BASIC 重构版) *
人工智能·microsoft·游戏引擎·游戏程序
步步为营DotNet4 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf