Spring.NET依赖注入框架学习--实例化容器常用方法


Spring.NET依赖注入框架学习---实例化容器常用方法

本篇学习实例化Spring.NET容器的俩种方式

1、通过XmlObjectFactory创建一个Spring.NET容器

IResource input = new FileSystemResource ("objects.xml");
IObjectFactory factory = new XmlObjectFactory(input);

这样就可以通过factory的GetObject(“objectName”);获取这个对象

2、通过IApplicationContext创建一个Spring.NET容器

IApplicationContext ctx = ContextRegistry.GetContext();

这样就可以通过IApplicationContext的GetObject(“objectName”);获取这个对象

程序例子

例子代码:Person.cs

namespace Spring.NET01
{
    public class Person
    {
        public Person()
        { }
        ~Person()
        { }
        public void print()
        {
            Console.WriteLine("我是一个Person对象");
        }
    }
}

App.config文件

<?xml version="1.0" encoding="utf-8" ?>

  
    "spring">
      
"context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
"objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> "config://spring/objects"> "http://www.springframework.net"> <object id="person1" type="Spring.NET01.Person,Spring.NET01"> object>

添加objects.xml  其中objects 的属性值必须加上

<?xml version="1.0" encoding="utf-8" ?>
"http://www.springframework.net"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.net
        http://www.springframework.net/xsd/spring-objects.xsd">
  <object id="person2" type="Spring.NET01.Person,Spring.NET01">
  object>

测试代码:

 class Program
    {
        static void Main(string[] args)
        {
            //普通对象创建
            Console.WriteLine("--------普通对象创建方法--------");
            Person person = new Person();
            person.print();

            //通过Spring.NET ioc IApplicationContext注入对象
            Console.WriteLine("--------IApplicationContext方法--------");
            IApplicationContext content = ContextRegistry.GetContext();
            Person bennanhai = (Person)content.GetObject("person1");
            bennanhai.print();


            //通过Spring.NET ioc XmlObjectFactory注入对象
            Console.WriteLine("--------XmlObjectFactory方法--------");
            IResource input = new FileSystemResource("objects.xml");
            IObjectFactory factory = new XmlObjectFactory(input);
            Person bennanhai2 = (Person)factory.GetObject("person2");
            bennanhai2.print();
            Console.Read();
        }
    }

运行结果

源代码工程下载

相关