net6内置IOC容器使用
1、创建控制台应用程序
2、Nuget引用Microsoft.Extensions.DependencyInjection
3、创建Business.IServices类库
创建接口IPower、IMicrophone.cs、IHeadphone
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Business.IServices 8 { 9 public interface IPower 10 { 11 } 12 }
1 namespace Business.IServices 2 { 3 public interface IMicrophone 4 { 5 6 } 7 }
1 namespace Business.IServices 2 { 3 public interface IHeadphone 4 { 5 } 6 }
4、创建Business.Services类库
创建类Power继承 IPower,Microphone继承IMicrophone,Headphone继承
1 using Business.IServices; 2 3 namespace Business.Services 4 { 5 public class Power :IPower 6 { 7 public Power(IMicrophone microphone) 8 { 9 Console.WriteLine($"{this.GetType().Name}被构造了"); 10 } 11 } 12 }
1 using Business.IServices; 2 3 namespace Business.Services 4 { 5 public class Microphone : IMicrophone 6 { 7 public Microphone() 8 { 9 Console.WriteLine($"{this.GetType().Name}被构造.."); 10 } 11 } 12 }
1 using Business.IServices; 2 3 namespace Business.Services 4 { 5 public class Headphone : IHeadphone 6 { 7 public Headphone(IPower power) 8 { 9 Console.WriteLine($"{this.GetType().Name}被构造..."); 10 } 11 } 12 }
5、修改Program.cs
1 using Business.IServices; 2 using Business.Services; 3 using Microsoft.Extensions.DependencyInjection; 4 5 { 6 //1、创建容器 7 ServiceCollection serviceDescriptors = new ServiceCollection(); 8 //2、注册抽象和具体普通类之间的关系 9 serviceDescriptors.AddTransient<IPower, Power>(); 10 serviceDescriptors.AddTransient<IMicrophone, Microphone>(); 11 serviceDescriptors.AddTransient<IHeadphone, Headphone>(); 12 //3、serviceDescriptions.builder 13 ServiceProvider serviceProvider = serviceDescriptors.BuildServiceProvider(); 14 15 //创建实例 16 IHeadphone headphone = serviceProvider.GetService<IHeadphone>(); 17 }
6、文件结构
7、启动调试
可以发现程序会依次执行Microphone、Power、Headphone的构造函数,然后创建Headphone实例
这是控制反转的构造函数注入,但一个实例需要被创建时,它的构造函数需要的参数实例会一层层追溯,然后创建构造函数参数需要的实例。