Unity运行时解析?

时间:2011-09-30 09:23:30

标签: c# unity-container ioc-container

我在控制台程序中有以下代码。

interface I { ...; string X { get; }; string Y {get; }; string Z {get; } ...}
class A : I {...}
class B : I {...}
class C : I {...}

程序接受命令行参数,如test.exe b -x 10 -z 20。它会创建一个B的瞬间,并将X设置为10,Z到20。

如何使用统一实现这一点?这可能是一个新手问题。

1 个答案:

答案 0 :(得分:3)

您需要针对同一个接口注册命名映射,并使用作为参数传递的名称进行解析。

var container = new UnityContainer();
container.RegisterType<I, A>("a");
container.RegisterType<I, B>("b");
container.RegisterType<I, C>("c");

I instance = container.Resolve<I>(args[0]);

阅读Registering Type Mappings with the Container了解