1. 程式人生 > >Spring.NET依賴註入框架學習--註入對象常見方法

Spring.NET依賴註入框架學習--註入對象常見方法

defaults bsp app actor res 代碼 -i ont 獲取

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" ?>
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core
" /> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> </configSections> <spring> <context> <!--元數據對象的來源--> <resource uri="config://spring/objects"></resource> </context> <objects xmlns="http://www.springframework.net"> <!--一個person對象--> <object id="person1" type="Spring.NET01.Person,Spring.NET01"> </object> </objects> </spring> </configuration>

添加objects.xml 其中objects 的屬性值必須加上

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="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>
</objects>

測試代碼:

 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();
        }
    }

運行結果

技術分享圖片

源代碼工程下載

Spring.NET依賴註入框架學習--註入對象常見方法