主要两个步骤:
1.注册服务
builder.Services.AddScoped<ITestServiceA, TestServieceA>();
2.使用
app.MapGet("TestServiceAShowA",([FromServices] ITestServiceA testServiceA) =>
{
return testServiceA.ShowA();
});
案例Demo
1.项目结构
2.MinimalApi.Interfaces代码
namespace MininalApi.Interfaces { public interface ITestServiceA { public string ShowA(); } }
namespace MininalApi.Interfaces { public interface ITestServiceB { public string ShowB(); } }
3.MinimalApi.Services代码
using MininalApi.Interfaces; namespace MininalApi.Services { public class TestServieceA : ITestServiceA { public TestServieceA() { Console.WriteLine($"{GetType().Name}被构造"); } public string ShowA() { return $"This is from {GetType().FullName} ShowA"; } } }
using MininalApi.Interfaces; namespace MininalApi.Services { public class TestServieceB : ITestServiceB { public ITestServiceA _testServiceA; public TestServieceB(ITestServiceA testServiceA) { _testServiceA = testServiceA; Console.WriteLine($"{GetType().Name}被构造"); } public string ShowB() { return $"This is from {GetType().FullName} ShowB 调用 {_testServiceA.ShowA()}"; } } }
4.MinimalApi.Demo1的Program.cs代码
using Microsoft.AspNetCore.Mvc; using MininalApi.Demo1; using MininalApi.Interfaces; using MininalApi.Services; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddScoped<ITestServiceA, TestServieceA>(); builder.Services.AddScoped<ITestServiceB, TestServieceB>(); WebApplication app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); #region IOC+DI FromServices来自于IOC容器 app.MapGet("TestServiceAShowA",([FromServices] ITestServiceA testServiceA) => { return testServiceA.ShowA(); }); app.MapGet("TestServiceBShowB", ([FromServices] ITestServiceB testServiceB) => { return testServiceB.ShowB(); }); #endregion app.Run();