体验Castle中从配置文件注册组件以及传递参数的一个小例子

最近看了一些IOC模式的介绍以及关于Castle的文章,从网上下下来关于Introducing Castle PartI的例子,不过在运行的时候出现错误,老是提示"Could not resolve non-optional dependency for smtpemailsender. Parameter 'host' type String"。最后决定自己做个简单的例子来体验一下,要做就作最简单的,只有一个组件。所需要的Castle的库是Castle.Windor.dll,Castle.DynamicProxy.dll,Caslte.Model.dll,Castle.MicroKernel.dll.
using System;

namespace IOC.Test.Component
{
    
/// <summary>
    
/// MyComponent1 's abstract。
    
/// </summary>

    public class MyComponent1
    
{
        
private String _name = null ;

        
/*
        // If I make the constructor with none parameters be valid. It will be ok. 
        public MyComponent1()
        {
            _name = "default";
        }
        
*/

        
public MyComponent1(String name)
        
{
            _name 
= name;
        }


        
public string Introducing()
        
{
            
return "My name is "+_name;
        }

    }

}

 

这里是调用的代码.

 

static void Main() 
{
    
//开始采用改构造函数创建实例不行,最后去网上需求hamment的帮助
    
//WindsorContainer container = new WindsorContainer( @"..\..\app.config" );
    
    WindsorContainer container 
= new WindsorContainer( new XmlInterpreter(  ) );
    
    
//这里如果组件已经在配置文件中说明的话,那么就不需要在这里重复注册了
    
//container.AddComponent("myCompo1",typeof(MyComponent1));
    MyComponent1 myCompo1 = (MyComponent1)container["myCompo1"];
    MessageBox.Show(
"hello,"+myCompo1.Introducing());
}


 

注意这里好象自己声明配置文件老是不生效,(我也正纳闷原因是啥呢,谁知道了告诉我)只有默认的配置文件才生效,对于Web的话,默认的是web.config,对于windows程序,默认是可执行程序名称.config.譬如我的可执行程序名字是IOC.Test.exe,那么默认的配置文件就是IOC.Test.exe.config,该文件和可执行程序放在同一个文件夹中。

配置文件的内容如下
<?xml version="1.0" encoding="utf-8" ?> 

<configuration>

    
<configSections>
        
<section name="castle"
          type
="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, 
                Castle.Windsor" />
    </configSections>

    
<castle>
        
<components>
            
<component id="myCompo1" Service="IOC.Test.Component.MyComponent1,IOC.Test" 

type
="IOC.Test.Component.MyComponent1,IOC.Test">
                
<parameters>
                    
<name>rhf</name>
                
</parameters>
            
</component>
        
</components>
    
</castle>

</configuration>


好了,运行一下吧。这时候你将会看到,"Hello,My name is rhf".这么简单也是费了我好大的一番周折的,这里谢谢Hamment和fabio的热心帮助,详细讨论情况请看http://forum.castleproject.org/posts/list/0/356.page#1688

另外大家关于Castle有啥问题的话,可以上http://forum.castleproject.org需求帮助,好心的Hamment会帮助你的。

posted @ 2006-01-13 11:25  雨人(ralpher)  阅读(742)  评论(2编辑  收藏  举报