Home > Development > Castle Windsor – Lifestyles in XML Configuration

Castle Windsor – Lifestyles in XML Configuration


I just wanted to discuss the two most commonly used options are Transient or Singleton. There are other options and you can setup your own custom LifeStyles. Well look at the following code now.

using System;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace CastleWindsorDemo
{

    public interface INotifier
    {
        void Notify();
    }

    public class Notifier : INotifier
    {
        private readonly string[] to;
        private readonly string from;

        public Notifier(string from, string[] to)
        {
            this.to = to;
            this.from = from;
        }

        public void Notify()
        {
            // Put code to send to people wishing to be notified here
        }
    }

    class Program
    {
        static void Main()
        {
            WindsorContainer container = new WindsorContainer(new XmlInterpreter());
            INotifier notifier1 = container.Resolve<INotifier>();
            INotifier notifier2 = container.Resolve<INotifier>();

            Console.WriteLine(notifier1.Equals(notifier2));


        }
    }
}


The default is singleton which means that you get the exact same object everytime you request it. Transient means that you get a new object everytime you request one. Heres the XML

<?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="notifier"
                 service="CastleWindsorDemo.INotifier,CastleWindsorDemos"
                 type="CastleWindsorDemo.Notifier,CastleWindsorDemos" lifestyle="singleton">
        <parameters>
          <from>
            system.predicate@gmail.com
          </from>
          <to>
            <array>
              <item>
                tim@hotmail.com
              </item>
              <item>
                tom@hotmail.com
              </item>
              <item>
                mary@hotmail.com
              </item>
            </array>
          </to>
        </parameters>
      </component>
    </components>
  </castle>
</configuration>

If you change the lifestyle to transient you get a new object test it out.

Blair….

Advertisements
Categories: Development Tags: , , ,
  1. No comments yet.
  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: