日期:2014-05-18  浏览次数:21036 次

c# winform spring.net
各位:请帮忙!
我的问题是,在winform中引用了spring框架,但一直报错误:未将对象引用设置到对象的实例
不知道还有哪里配置错误了,请各位大侠帮忙看看那。

我的配置文件及代码如下
  public partial class Form1 : Form
  {
  private HelloWorld helloWorldDAO;

  public HelloWorld HelloWorldDAO
  {
  get { return helloWorldDAO; }
  set { helloWorldDAO = value; }
  }

  public Form1()
  {
  InitializeComponent();
  }

  private void btn1_Click(object sender, EventArgs e)
  {
  //IApplicationContext context = ContextRegistry.GetContext();
   
  label1.Text = helloWorldDAO.sayHello("maoyong");//这儿报错:未将对象引用设置到对象的实例!

  //IApplicationContext context = ContextRegistry.GetContext();
  //object o = context.GetObject("HelloWorldDAO");
  //label1.Text = o.ToString();

  }
  }


配置文件如下:
<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">
  <object id="HelloWorldDAO" type="SpringHibernate.spring.HelloWorld" ></object>
   
  <object id="form1" type="SpringHibernate.Form1">
  <property name="HelloWorldDAO" ref="HelloWorldDAO" />
  </object>
   
   
  </objects>

------解决方案--------------------
那肯定会报错啊!你的没有值,如果你是放在不同的Form窗体的话至少也要实例化一下啊!
------解决方案--------------------
似乎都没有委托给spring进行依赖注入~
------解决方案--------------------
由于你的Form对象在Program.cs文件中是用“Application.Run(new Form1());”语句直接实例化出来的,并没有让Spring来实例化Form对象,这样一来Spring无法实现HelloWorld对象的注入。当你IApplicationContext context = ContextRegistry.GetContext();
object o = context.GetObject("HelloWorldDAO");
用时,你是从spring容器中手动拿出了HelloWorldDAO对象,调用时自然不会出错。
你要得调用无误,就必须也让spring来实例化Form对象,以给Form对象注入HelloWorldDAO对象。

如你在Program.cs中如此写则不会出错(当然出需要配置Form1对象):
IApplicationContext ctx = ContextRegistry.GetContext();
Form1 springEntity = (Form1 )ctx.GetObject("Form1 ");
Application.Run(Form1);

Windows Form程序与web程序是有差别的,如想以操作web的方式操作Windows Form是不行的。
所以你必须给spring容器一个入口点。IApplicationContext ctx = ContextRegistry.GetContext()这个东西虽然有点烦,但要用的地方还是要写。
------解决方案--------------------
原因是你的Form1类,不在spring.net托管范围中。
开发winform程序,正确的做法是在pragram.cs的main方法是IApplicationContext context = ContextRegistry.GetContext();。
然后 用context创建主窗体。

Form frm=(Form)context.GetObject("form1");
Application.run(frm);