Home > Development > Castle Windsor Parameters

Castle Windsor Parameters


Just a quick post on how to set required parameters on constructors on registered types. See the following code snippet.

The code below has an EmailService class required two constructor parameters, server and port. These are required to initialize the class. This is where the Parameters method shown below comes in initializing both of these values. Its telling the container what values to assign these values when it has to construct the class.

Hope this helps….

Blair…

using System.Net.Mail;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace CastleWindsorDemos
{

    public interface IEmailSender
    {
        void Send(MailMessage message);
    }

    public class EmailSender : IEmailSender
    {
        private readonly string server;
        private readonly int port;

        public EmailSender(string server, int port)
        {
            this.server = server;
            this.port = port;
        }

        public void Send(MailMessage message)
        {
            //Provide detail later
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer();
            container.Register(Component.For<IEmailSender>()
                                        .ImplementedBy<EmailSender>()
                                        .Named("emailsender")
                                        .Parameters(
                                            Parameter.ForKey("server").Eq("localhost"),
                                            Parameter.ForKey("port").Eq("4000")
                                        )
                                        .LifeStyle
                                        .Transient
                );

            IEmailSender sender = container.Resolve<IEmailSender>();


        }
    }
}
Advertisements
Categories: Development Tags: ,
  1. February 11, 2010 at 10:11 am

    I know it is confusing (will be addressed in vNext) but don’t use Parameters – use DependsOn.

    See docs here: http://using.castleproject.org/display/IoC/Fluent+Registration+API

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: