上次写了一个Unity的helloworld,就是将一个字符串注入到实例中。继续学习,这次注入数组类型和自定义的类。看代码……
public class TestClass { private string name; public string Name { get { return name; } set { name = value; } } } public class ArrayTest { private string name; public string Name { get { return name; } set { name = value; } } private string[] values; public string[] Values { get { return values; } set { values = value; } } private TestClass testClassSingle; public TestClass TestClassSingle { get { return testClassSingle; } set { testClassSingle = value; } } }
配置文件:
<configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <typeAliases> <typeAlias alias="string" type="System.String,mscorlib"/> <typeAlias alias="stringArray" type="System.String[],mscorlib"/> <typeAlias alias="arrayTest" type="UnityGameIOC.ArrayTest,UnityGameIOC"/> <typeAlias alias="testClassSingle" type="UnityGameIOC.TestClass,UnityGameIOC"/> </typeAliases> <containers> <container> <types> <type type="testClassSingle" name="testClassSingle"> <typeConfig> <property name="Name" propertyType="string"> <value type="string" value="单个类测试"/> </property> </typeConfig> </type> <type type="arrayTest"> <typeConfig> <!--注入一个字符串--> <property name="Name" propertyType="string"> <value type="string" value="dddddd" /> </property> <!--注入数组类型--> <property name="Values" propertyType="stringArray"> <array> <value type="string" value="1"/> <value type="string" value="2"/> <value type="string" value="3"/> <value type="string" value="4"/> </array> </property> <!--注入单个自定义的类--> <property name="TestClassSingle" propertyType="testClassSingle"> <dependency name="testClassSingle" type="testClassSingle"/> </property> </typeConfig> </type> </types> </container> </containers> </unity> </configuration>
在容器中调用:
class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers.Default.Configure(container); ArrayTest test = container.Resolve(typeof(ArrayTest)) as ArrayTest; foreach (string i in test.Values) { Console.WriteLine(i); } Console.WriteLine(test.Name); Console.WriteLine(test.TestClassSingle.Name); } }
运行截图:
总而言之,Unity和Castle IOC用着还挺像的。关于这些奇怪的标签没有弄太清楚,只搞清楚了一部分,等全弄清了再做笔记吧。