城堡windsor注册组件问题

时间:2010-09-29 10:32:19

标签: c# .net castle-windsor castle

您好 我第一次使用Castle项目,并且在控制台应用程序中使用容器注册组件时遇到了问题。 以下是castle.config文件:

<configuration>
  <configSections>
    <section name="castle"
        type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
  </configSections>
  <castle>
    <components>
      <component id="messageSender"
               type="CastleTest.SecretMessageSender, CastleTest">
        <parameters>SecretMessageSender
          <from>rahul.ragarwal@patni.com</from>
          <encoder>${encoder.null}</encoder>
        </parameters>
      </component>

      <component id="encoder.silly"
                service="CastleTest.IEncoder, CastleTest"
                type="CastleTest.SillyEncoder, CastleTest" />

      <component id="encoder.null"
                service="CastleTest.IEncoder, CastleTest"
                type="CastleTest.NullEncoder, CastleTest" />

    </components>
  </castle>

</configuration>

以下是我正在尝试注册我的组件的主要类:

namespace CastleTest
{
    class testNewCastle
    {
        static void Main(string[] args)
        {
            IWindsorContainer container = new WindsorContainer();

            **Tried various methods to register components here**

            SecretMessageSender sender = container.Resolve<SecretMessageSender>("messageSender");

            sender.SendMessage("Rahul", "Testing using Castle!");
            Console.Read();
        }
    }
}

以下是SecretMessageSender类:

namespace CastleTest
{
    public interface IEncoder
    {
        string Encode(string source);
    }

    public class SecretMessageSender
    {
        private readonly IEncoder _encoder;
        private readonly string _from;

        public SecretMessageSender(string from, IEncoder encoder)
        {
            _from = from;
            _encoder = encoder;
        }

        public void SendMessage(string to, string body)
        {
            Console.WriteLine("to: {0}\r\nfrom: {1}\r\n\r\n{2}", to, _from, _encoder.Encode(body));
        }
    }
}

请帮我运行此代码。

感谢。

1 个答案:

答案 0 :(得分:1)

container.Install(Configuration.FromAppConfig());

docs about installers

中的更多信息