容器中對象的部署分爲兩種方式:singleton和非singleton(java裏叫prototype)。這裏的singleton指的是“單例模式”,就是說當一個對象被定義爲singleton時,容器中就只會有一個共享的實例,任何時候通過id或別名請求該對象都會返回這個共享實例的引用(也就是說這個對象只會被創建一次)。當使用非singleton,或者說原型模式佈署時,每次請求對象都會創建新的實例。在某些場合,如果需要爲每個用戶返回單獨的用戶對象或其它對象,非singlton佈署模式就比較理想。Spring.NET默認爲singleton模式。每次調用GetObject方法時得到的都是同樣的實例;當singleton="false"時,每次調用GetObject方法時得到的則是不同的實例。
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<!--單例模式-->
<object id="personDao" type="SpringNetScopes.PersonDao, SpringNetScopes"/>
<!--非單例模式-->
<object id="person" type="SpringNetScopes.Person, SpringNetScopes" singleton="false" />
<!--調用時加載-->
<object id="personServer" type="SpringNetScopes.PersonServer, SpringNetScopes" lazy-init="true"/>
</objects>
namespace SpringNetScopes
{
public class PersonDao : IPersonDao
{
public PersonDao()
{
Console.WriteLine("PersonDao被實例");
}
public override string ToString()
{
return "我是PersonDao";
}
~PersonDao()
{
Console.WriteLine("PersonDao被銷燬");
}
public void Save()
{
Console.WriteLine("保存 Person");
}
}
public class Person
{
public Person()
{
Console.WriteLine("Person被實例");
}
public override string ToString()
{
return "我是Person";
}
~Person()
{
Console.WriteLine("Person被銷燬");
}
}
public class PersonServer
{
public PersonServer()
{
Console.WriteLine("PersonServer被實例");
}
public override string ToString()
{
return "我是PersonServer";
}
~PersonServer()
{
Console.WriteLine("PersonServer被銷燬");
}
}
}
[TestMethod]
public void CreateWithSingleton()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScopes/SpringNetScopes/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object obj1 = factory.GetObject("personDao");
object obj2 = factory.GetObject("personDao");
Assert.AreEqual(obj1, obj2);
}
[TestMethod]
public void CreateWithOutSingleton()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScopes/SpringNetScopes/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object obj1 = factory.GetObject("person");
object obj2 = factory.GetObject("person");
Assert.AreNotEqual(obj1, obj2);
}
[TestMethod]
public void CreateWithLazy()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScopes/SpringNetScopes/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object dao = factory.GetObject("personDao");
Console.WriteLine(dao.ToString());
object server = factory.GetObject("personServer");
Console.WriteLine(server.ToString());
}