首先,进行材料准备。我准备了一个MODEL类,一个SERVICE类
// Person.cs
namespace Model {
public class PersonModel {
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
}
// PersonService.cs
namespace Service {
public class PersonService {
private PersonModel person;
public PersonService() { }
public PersonService(PersonModel person) {
this.person = person;
}
public string PrintPersonInfo() {
return "姓名: " + person.Name
+ "性别: " + person.Sex
+ "年龄: " + person.Age;
}
}
}
Spring.NET配置的基本格式是:
<objects namespace="http://www.springframework.net">
<object id="" type="">
<property name="" value="" />
<property name="" ref="" />
</object>
</objects>
object - 需要配置的对象,相关属性:
- id - 对象ID
- type - 对象Type信息
property - 对象的成员,相关属性:
- name - 成员名称
- value - 成员是值类型时,给定初始值
- ref - 成员是对象时,给定对象ID
下面来看下PersonService类的配置,配置文件名:IocConfig.xml
<objects namespace="http://www.springframework.net">
<object id="personSrv" type="Service.PersonService, Service">
<property name="person" ref="personMdl" />
</object>
<object id="personMdl" type="Model.PersonModel, Model" />
</objects>
类信息配置完成后,进入最后一步,就是代码,我们来看下Program.cs的代码内容:
// Program.cs
static void Main(string[] args) {
// 告知Spring.NET配置文件
string configFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\IocConfig.xml";
IResource configSource = new FileSystemResource(configFilePath);
IObjectFactory objFactory = new XmlObjectFactory(configSource);
// 获取对象
PersonService personSrv = objFactry.CreateObject("personSrv", typeof(PersonService"), new object[] {
new PersonModel() {
Name = "Tom",
Age = 21,
Sex = "男"
}
}) as PersonService;
if (personSrv != null) {
Console.WriteLine(personSrv.PrintPersonInfo());
}
Console.Read();
}
这样,一个简单的Spring.NET IOC DEMO就实现了
参考资料: