S. *_*ert 17 c# ioc-container unity-container
我想做一个简单的多种类型注册解决方案(最终注入构造函数,但使用.Resolve来查看Unity是否能够执行此类操作.
在下面的每种情况下,Unity都会解析0应该解决的项目2.
是否有一些团结的转变可以打开2007年后的行为?还是我只是大失所想?
这是我的代码:
public interface IFoo {}
public class Foo1 : IFoo{}
public class Foo2 : IFoo{}
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IFoo, Foo1>();
container.RegisterType<IFoo, Foo2>();
// container.Resolve<IEnumerable<IFoo>>(); returns 0
// container.ResolveAll<IFoo>(); returns 0
var foos = container.Resolve<IFoo[]>();
Console.WriteLine(foos.Count());
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*.G. 35
在Unity中,只能有一个默认注册(没有名称的注册container.RegisterType<IFoo, Foo1>();
).如果执行多个默认注册,则最后一个注册获胜.
为了为同一个接口注册多个实现,您需要为这些注册分配名称:
container.RegisterType<IFoo, Foo1>("registration1");
container.RegisterType<IFoo, Foo2>("registration2");
Run Code Online (Sandbox Code Playgroud)
此外,Unity默认只了解数组.如果要将其解析为数组,那么您可以使用默认行为.否则,您需要在数组和您感兴趣的集合之间注册映射,例如:
container.RegisterType<IEnumerable<IFoo>, IFoo[]>();
Run Code Online (Sandbox Code Playgroud)
另一个重要注意事项是解析集合时不会返回默认注册.例如给出:
container.RegisterType<IFoo, Foo1>();
container.RegisterType<IFoo, Foo2>("registration1");
container.RegisterType<IFoo, Foo3>("registration2");
container.RegisterType<IEnumerable<IFoo>, IFoo[]>();
Run Code Online (Sandbox Code Playgroud)
如果您解决IEnumerable<IFoo>,结果将只包含Foo2和的实例Foo3,但不会有实例,Foo1因为默认注册不包括在内.