03_02_服务注册与消费

一、ServiceCollection

所有服务都是注册在ServiceCollection集合上的

根容器是通过BuildServiceProvider()创建出来的

ServiceCollection是存放服务注册信息的集合

不是容器,是信息,类型信息,登录了类型的名称,对应的接口,注册信息

根据注册信息进行实例化

服务描述类List<ServiceDescriptor>,服务类型,实现类型

如果构造函数参数需要其它实例,参数实例也必须在容器里已经存在

多个重载的构造函数 

依赖注入系统是根据构造函数来构造实例

有多个,会用哪个来构造呢?

new的时候也只能构造其中一个

如果一个类里面有3个构造函数,会选择哪一个呢?

 public static class Sample01
 {
     private interface ITest{ }

     public class Account: IAccount{}
     public class Message: IMessage{}
     public class Tool: ITool{}

     public class Test: ITest
     {
         public Test(IAccount account)
         {
             Console.WriteLine($"Ctor:Test(IAccount)");
         }

         public Test(IAccount account, IMessage message)
         {
             Console.WriteLine($"Ctor:Test(IAccount,IMessage)");
         }

         public Test(IAccount account, IMessage message, ITool tool)
         {
             Console.WriteLine($"Ctor:Test(IAccount,IMessage,ITool)");
         }
     }

     public static void Run()
     {
         var test = new ServiceCollection()
             .AddTransient<IAccount, Account>()
             .AddTransient<IMessage, Message>()
             .AddTransient<ITest, Test>()
             .BuildServiceProvider()
             .GetService<ITest>();
     }
 }

在所有符合条件,选择参数最多的那一个,超集

第三个ITool tool没有注册,所以会选择第二个

 

2、如果参数相同,会选择哪一个呢?

如果某个构造函数的参数类型集合,能够成为所有合法构造函数参数类型集合的超集

public static class Sample02
{
    private interface ITest{ }

    public class Account: IAccount{}
    public class Message: IMessage{}
    public class Tool: ITool{}
    public class Test: ITest
    {
        public Test(IAccount account, IMessage message)
        {
            Console.WriteLine($"Ctor:Test(IAccount)");
        }

        public Test(IMessage message, ITool tool)
        {
            Console.WriteLine($"Ctor:Test(IAccount,IMessage)");
        }
    }

    public static void Run()
    {
        var test = new ServiceCollection()
            .AddTransient<IAccount, Account>()
            .AddTransient<IMessage, Message>()
            .AddTransient<ITool, Tool>()
            .AddTransient<ITest, Test>()
            .BuildServiceProvider()
            .GetService<ITest>();
    }
}

都不会,不满足某一个构造函数里面的参数集合能够成为超集。

两个条件:

1、都存在在容器

2、参数集合存在超集

抛异常:

Reference knowledge, personality instructions, deep thinking, 100/5000 AI translation, translation, AI big model translation, unable to activate type "ConsoleApp1. Sample02+Test". The following constructors are ambiguous

无法激活类型“ConsoleApp1.Sample02+Test”。以下构造函数存在歧义

Void .ctor(ConsoleApp1.IAccount, Zhaoxi.ConsoleApp1.IMessage)
Void .ctor(ConsoleApp1.IMessage, Zhaoxi.ConsoleApp1.ITool)”

两个构造函数,没有一个是超集的

选择无能

一个常见的坑

 

posted on 2026-01-26 17:35  张彦山  阅读(2)  评论(0)    收藏  举报