Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从unity容器中按名称获取类型的所有实例?_C#_.net_Dependency Injection_Inversion Of Control_Unity Container - Fatal编程技术网

C# 如何从unity容器中按名称获取类型的所有实例?

C# 如何从unity容器中按名称获取类型的所有实例?,c#,.net,dependency-injection,inversion-of-control,unity-container,C#,.net,Dependency Injection,Inversion Of Control,Unity Container,我有一个容器,其中包含一些已注册的实例,如: container.RegisterInstance(typeof(Interface1), "Mapping1", new Class1("1")) .RegisterInstance(typeof(Interface1), "Mapping1", new Class1("2")) .RegisterInstance(typeof(Interface1), "Mapping2", new Class1("3"))

我有一个容器,其中包含一些已注册的实例,如:

container.RegisterInstance(typeof(Interface1), "Mapping1", new Class1("1"))
         .RegisterInstance(typeof(Interface1), "Mapping1", new Class1("2"))
         .RegisterInstance(typeof(Interface1), "Mapping2", new Class1("3"))
         .RegisterInstance(typeof(Interface1), "Mapping2", new Class1("4"));
那么,我如何才能将Interface1类型的所有实例命名为Mapping1呢? 调用代码如下所示:

var instances = container.ResolveAll<Interface1>("Mapping1");

感谢您的回答。

您可以创建一个扩展方法来处理此问题。看看这篇文章。它帮助了我,我想它回答了你的问题:

您可以创建一个扩展方法来处理此问题。看看这篇文章。它帮助了我,我想它回答了你的问题:

您不能有多个具有相同名称和类型组合的注册。每个新注册都将覆盖以前的注册。

您不能有多个具有相同名称和类型组合的注册。每个新注册都将覆盖上一个。

我不确定这样注册实例是否会产生您想要的结果。RegisterInstance将对象注册为单例,因此根据定义,不能有多个同名的单例。从上面提供的示例中,container.ResolveAll将只返回2个实例。

我不确定这样注册实例是否会产生您想要的结果。RegisterInstance将对象注册为单例,因此根据定义,不能有多个同名的单例。从上面提供的示例中,container.ResolveAll将只返回2个实例。

我认为对于以下情况,我在中找到了一个新的答案:

RegisterType(typeof(IService), typeof(Service));
RegisterType(typeof(IService), typeof(Service),  "Name-1");
RegisterType(typeof(IService), typeof(Service1), "Name-2");
RegisterType(typeof(IService), typeof(Service1), "Name-3");
RegisterType(typeof(IService), typeof(Service1), "Name-4");
历史上,调用ResolveAll Resolve Unity时只返回4个项目,其中包含 “Name-x”,但现在已经添加了对IEnumerable的支持。像 反对一切,解决一切 Resolve将返回所有注册 令人满意的恶习。因此,在上面的示例中,它将返回所有5个 对象


我知道它不是同一个代码,因为您注册的是实例而不是类型,但它可能会有所帮助,我还没有测试过它。

我想我在中找到了一个新的答案,其中,对于以下情况:

RegisterType(typeof(IService), typeof(Service));
RegisterType(typeof(IService), typeof(Service),  "Name-1");
RegisterType(typeof(IService), typeof(Service1), "Name-2");
RegisterType(typeof(IService), typeof(Service1), "Name-3");
RegisterType(typeof(IService), typeof(Service1), "Name-4");
历史上,调用ResolveAll Resolve Unity时只返回4个项目,其中包含 “Name-x”,但现在已经添加了对IEnumerable的支持。像 反对一切,解决一切 Resolve将返回所有注册 令人满意的恶习。因此,在上面的示例中,它将返回所有5个 对象

我知道它不是同一个代码,因为您注册的是实例而不是类型,但它可能会有所帮助,我还没有测试过它