『Spring.NET』IoC 容器中对象的作用域

主要内容及结构参考自:@刘冬.NET官方文档

 

一些必要的说明


You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular object definition, but also the scope of the objects created from a particular object definition. This approach powerful and flexible in that you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the .NET class level. Objects can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes, three of which are available only if you use a web-aware IApplicationContext.

你不仅可以控制依赖项和配置项的值,还可以控制注入对象的作用域。这让你可以选择通过配置而创建的对象的作用域去代替在类级别控制。对象可以被定义以便作用域数量的一个中部署:在盒子之外,Spring框架支持5种作用域,3种只有你使用一个web-aware的IApplicationContext时被支持。

上面的话主要告诉我这样一件事情:

  • 在Spring.NET中,我有5种对象的作用域可以选择。主要使用的应该是其中的两种。

 

可用的作用域及其描述


Scope Description
singleton Scopes a single object definition to a single object instance per Spring IoC container.
每一个容器中,只能有一个相应实例。
PS: 这个一般是被程序默认指定的。
prototype Scopes a single object definition to any number of object instances.
为所有对象实例划定一个唯一的对象定义。
request Scopes a single object definition to the lifecycle of a single HTTP request; that is, each and every HTTP request has its own instance of an object created off the back of a single object definition. Only valid in the context of a web-aware Spring ApplicationContext.
session

Scopes a single object definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application Scopes a single object definition to the lifecycle of a web application. Only valid in the context of a web-aware Spring ApplicationContext.

 

 

 

 

 

 

 

 

 

 

 

一些说明

  • 对于singleton的对象,是只有一个在其容器中的,也就是说,哪怕之后又调用了一遍GetObject方法,其得到的还是之前创建的那个实例。相当于是使用的单例模式创建的对象。
  • singleton是默认被指定的,也就是说,如果你没有显示的指定,那么程序会自动为对象指定这个作用域。
  • prototype,也可以说是非singleton,也就是说,这个是没有使用单例模式的创建对象的方式。每调用一次GetObject方法,都会生成一个新的实例。
  • prototype是需要被显示指定的。 object id="exampleObject" type="Examples.ExampleObject, ExamplesLibrary" scope="prototype"
  • request、session、application这三个是在Spring.NET 1.1之后才被加上的,全用的时候需要注意Spring.NET的版本。
posted @ 2012-02-01 15:44  莫不逢  阅读(807)  评论(0编辑  收藏  举报