.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配置依赖注入结束。

相关推荐
一只码代码的章鱼6 分钟前
计算机网络 应用层 笔记 (电子邮件系统,SMTP,POP3,MIME,IMAP,万维网,HTTP,html)
笔记·计算机网络·microsoft
时光追逐者20 小时前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
唐青枫1 天前
dotnet LINQ 使用简明教程
c#·.net
流星白龙1 天前
【Linux】23.进程间通信(2)
linux·数据库·microsoft
流形填表2 天前
Pdf to forms如何实现?如何在3分钟内将PDF自动转换为Microsoft Forms
microsoft·pdf·c#
hez20103 天前
Brainfly: 用 C# 类型系统构建 Brainfuck 编译器
c#·.net·aot·.net core·clr·compiler
果冻人工智能3 天前
“星门计划对AI未来的意义——以及谁将掌控它”
大数据·人工智能·microsoft·自然语言处理·llama·ai员工
xxxxxue3 天前
.Net / C# 繁体中文 与 简体中文 互相转换, 支持地方特色词汇
c#·.net·简体中文·繁体中文·繁体·简体·日文
Zda天天爱打卡3 天前
【深度分析】微软全球裁员计划不影响印度地区,将继续增加当地就业机会
microsoft·创业创新
kcarly3 天前
Microsoft Power BI:融合 AI 的文本分析
人工智能·gpt·microsoft·bi