1,使用nuget安装SPring.Core。安装这个的同时,会把Common.Logging,Common.Logging.Core也装上。
2,建立对象配置xml文件。如图Objects.xml。(文件的属性要设置为嵌入的资源,不然在实例化容器的时候会找不到资源抛异常。)
3,实例化容器,三种方法
(1)通过物理路径读取对象配置文件进行容器实例化
////// 物理路径方式 /// static void RegSpringContainer() { IResource objXml = new FileSystemResource(@"D:\Demo\NHibernateTest\NHibernateTest\Objects.xml"); IObjectFactory factory = new XmlObjectFactory(objXml); UserService service = factory.GetObject("UserService") as UserService; User model = service.Find(1); string name = model != null ? model.UserName : ""; Console.WriteLine(name); }
(2) 通过程序集读取配置文件,对容器进行实例化(通过此方法,须把Objects.xml文件属性设置为嵌入的资源,不然找不到配置文件抛异常)
////// 程序集方式 /// static void RegSpringAssembly() { string[] xmlFiles = new string[] { //"file://Objects.xml", "assembly://NHibernateTest/NHibernateTest/Objects.xml" }; IApplicationContext context = new XmlApplicationContext(xmlFiles); IObjectFactory factory = (IObjectFactory)context; UserService service = factory.GetObject("UserService") as UserService; User model = service.Find(1); string name = model != null ? model.UserName : ""; Console.WriteLine(name); }
这种方式需满足URI语法:
file://文件名 assembly://程序集名/命名空名/文件名(3) ,对过配置文件App.config或Web.config添加自定义配置节点,读取配置文件,实例化容器。(通过此方法,须把Objects.xml文件属性设置为嵌入的资源,不然找不到配置文件抛异常)
////// 配置文件方式 /// static void RegSpringConfig() { IApplicationContext context = ContextRegistry.GetContext(); UserService service = context.GetObject("UserService") as UserService; User model = service.Find(1); string name = model != null ? model.UserName : ""; Console.WriteLine(name); }
测试程序:
static void Main(string[] args) { //RegSpringContainer(); RegSpringAssembly(); //RegSpringConfig(); }
参考:http://www.cnblogs.com/GoodHelper/archive/2009/10/25/SpringNET_Config.html