spring.net支持从构造器中注入属性(包括内联属性以及值属性)注入, 构造函数注入, 以及很常见的接口注入.
直接给代码:
namespace IOCdemo0820
{
public class People
{
public string Name { get; set; }
public string Age { get; set; }
public People Friend { get; set; }
}
}
namespace IOCdemo0820
{
public class PersonDao
{
private People argPerson;
private int intProp;
public PersonDao(People arg, int intProp)
{
this.argPerson = arg;
this.intProp = intProp;
}
public void Get()
{
//构造函数注入的整型参数
Console.WriteLine(string.Format("intProp:{0}", intProp));
//构造函数注入的Person
Console.WriteLine(string.Format("argPerson Name:{0}", argPerson.Name));
Console.WriteLine(string.Format("argPerson Age:{0}", argPerson.Age));
//内联对象Friend
Console.WriteLine(string.Format("argPerson Friend Name:{0}", argPerson.Friend.Name));
Console.WriteLine(string.Format("argPerson Friend Age:{0}", argPerson.Friend.Age));
//内联对象的循环引用
Console.WriteLine(string.Format("argPerson Friend Friend Name:{0}", argPerson.Friend.Friend.Name));
Console.WriteLine(string.Format("argPerson Friend Friend Age:{0}", argPerson.Friend.Friend.Age));
}
}
}
<object id="people" type="IOCdemo0820.People, IOCdemo0820">
<!--属性值类型注入-->
<property name="Name" value="Dennis"/>
<property name="Age" value="27"/>
<!--内联对象注入-->
<property name="Friend">
<object type="IOCdemo0820.People, IOCdemo0820">
<property name="Name" value="Beggar"/>
<property name="Age" value="23"/>
<property name="Friend" ref="people"/>
</object>
</property>
</object>
<object id="personDao" type="IOCdemo0820.PersonDao, IOCdemo0820">
<!--构造器注入-->
<constructor-arg name="arg" ref="people"/>
<constructor-arg name="intProp" value="1"/>
</object>
PersonDao personDao = (PersonDao) ctx.GetObject("personDao");
personDao.Get();