1.使用属性依赖注入:
XML
<object id="exampleObject" type="Examples.ExampleObject, ExamplesLibrary"> <!-- setter injection using the ref attribute --> <property name="objectOne" ref="anotherExampleObject"/> <property name="objectTwo" ref="yetAnotherObject"/> <property name="IntegerProperty" value="1"/> </object> <object id="anotherExampleObject" type="Examples.AnotherObject, ExamplesLibrary"/> <object id="yetAnotherObject" type="Examples.YetAnotherObject, ExamplesLibrary"/>
public class ExampleObject { private AnotherObject objectOne; private YetAnotherObject objectTwo; private int i; public AnotherObject ObjectOne { set { this.objectOne = value; } } public YetAnotherObject ObjectTwo { set { this.objectTwo = value; } } public int IntegerProperty { set { this.i = value; } } }上面的示例非学容易理解,从XML中可以看出其配置的name对应的属性关联,ref则对应类名,value为直接附值
2.使用静态工厂依赖注入:
<object id="exampleObject" type="Examples.ExampleFactoryMethodObject, ExamplesLibrary" factory-method="CreateInstance"> <constructor-arg name="objectOne" ref="anotherExampleObject"/> <constructor-arg name="objectTwo" ref="yetAnotherObject"/> <constructor-arg name="intProp" value="1"/> </object> <object id="anotherExampleObject" type="Examples.AnotherObject, ExamplesLibrary"/> <object id="yetAnotherObject" type="Examples.YetAnotherObject, ExamplesLibrary"/>
public class ExampleFactoryMethodObject { private AnotherObject objectOne; private YetAnotherObject objectTwo; private int i; // a private constructor private ExampleFactoryMethodObject() { } public static ExampleFactoryMethodObject CreateInstance(AnotherObject objectOne, YetAnotherObject objectTwo, int intProp) { ExampleFactoryMethodObject fmo = new ExampleFactoryMethodObject(); fmo.AnotherObject = objectOne; fmo.YetAnotherObject = objectTwo; fmo.IntegerProperty = intProp; return fmo; } // Property definitions }上面类的注入方式已由属性变成了静态工厂方式,注意XML中的factory-method="CreateInstance",这里已经配置好了工厂方法的名称