Spring.Net

Never、C發表於2014-10-07

 

Spring.Net 本質就是一個抽象工廠。容器(IApplicationContext)透過配置建立一個物件。

1.建立物件(IoC)

<?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"/>
    </context>
    <objects xmlns="http://www.springframework.net">
      <description>An  example that demonstrates simple IoC features.</description>
    </objects>
  </spring>
</configuration>
初始化容器配置

自動提示功能可透過schema檔案約束:spring-objects-1.3.xsd

在object節點匯入名稱空間即可。

 

初始化容器物件:

IApplicationContext ctx = ContextRegistry.GetContext();

需要引用2個程式集:Common.Logging.dll和Spring.Core.dll

 

配置一個型別:

<objects xmlns="http://www.springframework.net">
<description>An example that demonstrates simple IoC features.</description>
<object name="{呼叫名}" type="{類的限定名}, {專案名}">
</object>
</objects>
配置一個待例項化的類

 

例項化:

ctx.GetObject("{呼叫的名字}") 

 

2.依賴注入(DI)

<objects xmlns="http://www.springframework.net">
  <object name="MyMovieLister"      type="Spring.Examples.MovieFinder.MovieLister, Spring.Examples.MovieFinder">
    <property name="movieFinder" ref="MyMovieFinder"/>
  </object>
  <object name="MyMovieFinder"        type="Spring.Examples.MovieFinder.SimpleMovieFinder, Spring.Examples.MovieFinder"/>
  </object>
</objects>
屬性注入
  <object name="AnotherMovieFinder"      type="Spring.Examples.MovieFinder.ColonDelimitedMovieFinder, Spring.Examples.MovieFinder">
    <constructor-arg index="0" value="movies.txt"/>
  </object>
構造器引數注入