NoSuchObjectDefinition发现异常:找不到对象的定义

时间:2013-09-20 13:02:11

标签: c# console-application spring.net

我是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>

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

提前致谢..

1 个答案:

答案 0 :(得分:0)

你的xml文件就像一个应用程序配置文件(app.config),但是当像你一样使用XmlApplicationContext时,它应该是一个普通的xml文件,例如参见this example一个普通的xml配置文件。

基本上,您的XMLFile1.xml应该是:

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

记录在section 5.2.2 of the docs