Spring.NET IOC简单DEMO

首先,进行材料准备。我准备了一个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;
        }
    }
}


接下来对PersonService进行配置。

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就实现了
参考资料:

SPRING.NET 1.3.2 学习3--IOC容器

SPRING.NET 1.3.2 学习5--依赖注入

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值