上一篇博客中总结了从面向接口创建对象到利用ioc容器去读取配置好的对象。这篇博客总结一下读取包含了spring.net对象定义的xml文件或.config配置文件,
利用IApplicationContext的一个实现类XmlApplicationContext去读取。只不过写代码的地方不一样:1.一种是写到程序中。2.另一种是在.net的.config文件中添加自定义配置节点。
1.写到程序中。
string[] xmlFiles = new string[] { "assembly://CreateObjects/CreateObjects/Objects.xml" //Objects.xml是定义了对象的xml文件 }; IApplicationContext context = new XmlApplicationContext(xmlFiles); //读取xml文件,实例化上下文
2.另一种是在.net的.config文件中添加自定义配置节点。
<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> <!--spring容器上下文,统一入口,创建的对象在config://spring/objects这个位置--> <context type="Spring.Context.Support.XmlApplicationContext, Spring.Core"> <resource uri="assembly://CreateObjects/CreateObjects/Objects.xml"/> </context> </spring>
利用ContextRegistry实例化上下文,对容器中对象进行访问。
IApplicationContext ctx = ContextRegistry.GetContext();
值得注意的是如果对象是配置到了xml文件中,需要修改xml属性中“复制到输出目录”:始终复制;“生成操作”:嵌入的资源。
总结:
个人更倾向于后者去访问容器中的对象,因为是写到了配置文件中,便于修改,更符合spring.net的思想。
原文:http://blog.csdn.net/suneqing/article/details/44673583