为了让接口程序更加模块化和可测试,采用依赖注入的方式调用接口方法。
在NuGet里面搜索Microsoft.Extensions.DependencyInjection,并进行安装。

/*************************************
* 功 能:测试Service实现类
* 创 建 人:********
* 创建时间:2024-02-19
* ***********************************/
namespace Application
{
///
/// 测试Service.
///
public class TestService : ITestService
{
///
/// 测试查询.
///
public List<AgentGroup> TestSelect()
{
var list = SqlSugarORM.SqlSugarHelper.Db.Queryable<AgentGroup>().ToList();
return list;
}
}
}
/*************************************
* 功 能:测试Service 接口类声明类
* 创 建 人:********
* 创建时间:2024-02-19
* ***********************************/
namespace CadApplication.Service
{
public interface ITestService
{
///
/// 测试查询.
///
List<AgentGroup> TestSelect();
}
}
/*************************************
* 功 能:测试控制器
* 创 建 人:********
* 创建时间:2024-02-19
* ***********************************/
namespace WebApi.Controllers
{
///
/// 测试Controller.
///
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly ITestService _testService;
///
/// 构造函数.
///
///
public TestController(ITestService testService)
{
_testService=testService;
}
///
/// 测试查询.
///
[Route("TestSelect")]
[HttpPost]
public List<AgentGroup> TestSelect()
{
return _testService.TestSelect();
}
}
}
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();
至此.net配置依赖注入结束。