1

我是 Spring.Net 的新手。我创建了简单的控制台应用程序并想要获取类对象。

代码:

namespace ConsoleApplicationApring
{
    class Program
    {
        static void Main(string[] args)
        {
            IApplicationContext context = new XmlApplicationContext(
                @"E:\VS Projects\ConsoleApplicationApring\ConsoleApplicationApring\XMLFile1.xml");

            Car car = (Car)context.GetObject("MyCar");
        }
    }

    public interface ICar
    {
        void Move();
    }

    public class Car : ICar
    {

        public void Move()
        {
            Console.WriteLine("In the Car");
        }
    }
}

XML 文件:

<?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"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
      <object name="MyCar"
      type="ConsoleApplicationApring.Car, ConsoleApplicationApring" >
      </object>
    </objects>
  </spring>
</configuration>

当我运行应用程序时,我在 "" NoSuchObjectDefiniation found 线上得到异常Car car = (Car)context.GetObject("MyCar");:找不到对象的定义 [MyCar]

提前致谢..

4

1 回答 1

0

你的xml文件就像一个应用程序配置app.config文件(XmlApplicationContext

基本上,你XMLFile1.xml应该是这样的:

<objects xmlns="http://www.springframework.net">
  <object name="MyCar"
  type="ConsoleApplicationApring.Car, ConsoleApplicationApring" >
  </object>
</objects>

这记录在docs 的第 5.2.2 节中

于 2013-09-21T15:03:45.793 回答