1、添加类库项目 Demo02.Interface、Demo02.Service
2、创建ITestServiceA接口
namespace Demo02.Interface { public interface ITestServiceA { public string ShowA(string info); } }
3、创建TestServiceA.cs实现ITestServiceA接口
using Demo02.Interface; namespace Demo02.Service { public class TestServiceA : ITestServiceA { public TestServiceA() { Console.WriteLine($"{GetType().Name} 被构造~"); } public string ShowA(string info) { return $"this is from {GetType().Name} ShowA:{info}"; } } }
4、Demo02.Interface、Demo02.Service生成项目,在Demo02中添加依赖项。
5、Program.cs中注册抽象与具体的关系
#region 注册抽象与具体的关系 { builder.Services.AddTransient<ITestServiceA, TestServiceA>(); } #endregion
6、创建IOCContainerController,注入ITestServiceA,测试使用。
using Demo02.Interface; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Demo02.Controllers { /// <summary> /// IOC容器使用 /// </summary> [ApiVersion("1.0")] [Route("[controller]/V{version:apiVersion}")] [ApiController] public class IOCContainerController : ControllerBase { private readonly ILogger<IOCContainerController> _logger; private readonly ITestServiceA _ITestServiceA; /// <summary> /// 构造函数 /// </summary> /// <param name="logger"></param> /// <param name="iTestServiceA">注入ITestServiceA</param> public IOCContainerController(ILogger<IOCContainerController> logger,ITestServiceA iTestServiceA) { _logger = logger; _ITestServiceA = iTestServiceA; } /// <summary> /// GET /// </summary> /// <returns></returns> [HttpGet()] public string GetString() { return _ITestServiceA.ShowA("IOC容器使用成功"); } } }
7、接口测试
标签:容器,string,core,ITestServiceA,Demo02,Interface,net,public From: https://www.cnblogs.com/yyd-sun/p/17014759.html