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

本文介绍了如何在.NETCore应用中使用依赖注入(DI)方式,包括安装Microsoft.Extensions.DependencyInjection库、创建Service实现和声明、在控制器和启动类中注入,以及在单独类中使用DI。着重展示了如何测试Service接口和实现类。
摘要由CSDN通过智能技术生成

一、概述

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

二、安装Microsoft.Extensions.DependencyInjection

在NuGet里面搜索Microsoft.Extensions.DependencyInjection,并进行安装。
在这里插入图片描述

三、代码编写

3.1 创建Service 实现类
/*************************************
*  功    能:测试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 声明类
/*************************************
*  功    能:测试Service 接口类声明类
*  创 建 人:********
*  创建时间:2024-02-19
* ***********************************/

namespace CadApplication.Service
{

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

    }
}

3.3 控制器里面通过构造函数注入
/*************************************
 *  功    能:测试控制器
 *  创 建 人:********
 *  创建时间: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
builder.Services.AddSingleton<ITestService, TestService>();

整体的Program.cs代码如下:


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 如果需要在某一个类里面单独调用也可以这样写
 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配置依赖注入结束。

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Dependency Injection Principles, Practices, and Patterns teaches you to use DI to reduce hard-coded dependencies between application components. You'll start by learning what DI is and what types of applications will benefit from it. Then, you'll work through concrete scenarios using C# and the .NET framework to implement DI in your own projects. As you dive into the thoroughly-explained examples, you'll develop a foundation you can apply to any of the many DI libraries for .NET and .NET Core. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Dependency Injection (DI) is a great way to reduce tight coupling between software components. Instead of hard-coding dependencies, such as specifying a database driver, you make those connections through a third party. Central to application frameworks like ASP.NET Core, DI enables you to better manage changes and other complexity in your software. About the Book Dependency Injection Principles, Practices, and Patterns is a revised and expanded edition of the bestselling classic Dependency Injection in .NET. It teaches you DI from the ground up, featuring relevant examples, patterns, and anti-patterns for creating loosely coupled, well-structured applications. The well-annotated code and diagrams use C# examples to illustrate principles that work flawlessly with modern object-oriented languages and DI libraries. What's Inside Refactoring existing code into loosely coupled code DI techniques that work with statically typed OO languages Integration with common .NET frameworks Updated examples illustrating DI in .NET Core About the Reader For intermediate OO developers.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码写到35岁

你的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值