.net core (.net 6) IOC容器注入--内置容器
注:内置容器仅支持构造函数方式注入(经过实验[FromServices]注入也支持)
参考:面试疑问:.NET Core依赖注入有三种方式是真的吗?
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、接口测试