Castle Windsor Tutorial Part 1

Download Example

Inversion of Control (IOC) using Castle Windsor and WPF

You have probably found this article because you have been searching around on the internet and not been able to find something that shows you an end to end solution of how to use an Inversion of Control (IOC) container. I tried to find a good basic example of using Castle but all the examples were very difficult to follow and didn’t present a decent break down of what was happening. So in a break from my normal quick code breakdown i will try and provide a reasonable explanation of the code.

This tutorial will cover the following:-

  1. Installing Components for Castle Windsor
  2. Resolving Components using Castle Windsor

What wont be covered:

  1. Using NuGet
  2. Explanation of all WPF syntax

So lets get down to it. We will be using the Castle Windsor IOC container; specifically version 3.2 which you can find here [Castle Windsor 3.2]

Dependency Injection

An Inversion of Control system allows you to inject dependencies into your code without having to do it yourself. Most people will be familiar with dependency injection using interfaces. A brief explanation of this is shown below.

    public interface IShape {
        void Draw();
    }

    public class Circle : IShape {

        public void Draw()
        {
            Console.WriteLine("Draws Circle");
        }
    }
    public class Square : IShape
    {

        public void Draw()
        {
            Console.WriteLine("Draws Square");
        }
    }

    public class Example {
        public void DrawSomething(IShape shape) {
            shape.Draw();
        }
    }

    public class App {
        public App(){
            Example demo = new Example();
            demo.DrawSomething(new Circle());
            demo.DrawSomething(new Square());
        }
    }

This is an example that’s used time and time again, but there is a reason its used its because its a good one. You should be able to see what’s happening in the example. We have a simple DrawSomething method which takes an IShape interface, as we supply a new instance or Circle or Square to the method the corresponding message is written to the console. This is a very basic example of dependency injection, IOC takes it one step further.

Mandatory and Optional Dependencies

First thing to note is that when using an IOC container there are two basic types of dependency.

A mandatory dependency is something that is supplied to the constructor of the type that you are creating, this is something that you are “planning” on using from the outset of the instance.

An Optional dependency is something that is set after the object has been initialized, in the examples that you will see this relates to properties on the models that are created.

A property can only be injected if:-

  • It is set as public and has a public setter
  • Its an instance property
  • It does not implement the [DoNotWire] attribute

Inversion Of Control

The example that i will present will be very simplistic but fingers crossed will make some sense.

To implement IOC correctly you should only have a single place where the IOC’s Register, Resolve and Release methods are called. If this seems a little far fetched please stick with me, and i will prove it. If you are calling the IOC’s Resolve method in numerous places then its being done incorrectly; what you are using in that instance is the Service Locator pattern, and while it has its place its not true IOC.

If you are working on large, possibly older project that doesn’t currently implement IOC then its a big change to switch to using IOC, in this instance
i think that you would be forgiven if you use IOC as a service locator in the short term as you progress to a true IOC enviroment. If nothing else it will help you identify the points in your code that require interfaces and also importantly, it will introduce you to what IOC is capable of.

I have written the example code using Visual Studio 2010. We will be creating a very simple WPF application. If your not familiar with WPF please try and read through this example anyway, since WPF is beyond the scope of this article I won’t be going into the finer points if the language.

So, starting with a simple WPF (C#) project called IOCExample. The VS WPF template creates a number of files for you, one of these is called App.xaml which has a code behind file called App.xaml.cs. Lets begin by removing the Startup URI for the application, double click on the App.xaml file so that you get the xaml code view which should look like this.

<Application x:Class="IOCExample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    <Application.Resources>
<Application>

The App.xaml file is the starting point for all WPF applications. The StartupURI tells the application which form it should show first. If you look in the solution explorer you will see the file that it referenced “MainWindow.xaml”, we are going to launch this form later using IOC.

We want to remove the StartupURI value, the result should look like this.

<Application x:Class="IOCExample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
         
    <Application.Resources>
<Application>

Save the App.xaml file and open the App.xaml.cs file, this is a very basic class that has many different methods which can be overridden. Currently it should look like this

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace IOCExample
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// <summary>
    public partial class App : Application
    {
    }
}

This is where we will create the reference to the Castle Windsor container. Lets override a method; override the OnStartup
method, your code should now look like this.

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
        }
    }

Using the NuGet package manager, download the Castle Windsor 3.2 package. Once you have done this lets add our Castle code into our solution. There are a number of ways to configure Castle but I will try and show a simple method that should be easy to follow; Change the App class so that it looks like this.

using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace IOCExample
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// <summary>
    public partial class App : Application
    {
        IWindsorContainer container;
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            container = new WindsorContainer();
        }
    }
}

We have created a private field for the IWindsorContainer interface and set the field from within the OnStartup method.

Now lets create some interfaces and classes that we can use in our example. Strictly speaking you should create each interface / class etc in there own separate .cs file, but for clarity i will break with this formality and group them together.

create a new class file and call it interfaces.cs, copy the following code into it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOCExample
{
    public interface IStartPageModel
    {
        IHeading Heading { get; set; }
        IHeading SubHeading { get; set; }
    }
    
    public interface IHeading
    {
        string Caption { get; set; }
        string Value { get; set; }
    }

    public interface IStartPageViewModel
    {
        IStartPageModel viewmodel { get; set; }
        IStartPageModel Get();
    }
}

Now create another class file and call it classes.cs and copy the following code into it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOCExample
{
    public class StartPageModel : IStartPageModel
    {
        public IHeading Heading { get; set; }
        public IHeading SubHeading { get; set; }
    }

    public class Heading : IHeading
    {
        public string Caption { get; set; }
        public string Value { get; set; }
    }

    public class StartPageViewModel : IStartPageViewModel
    {

        public IStartPageModel viewmodel { get; set; }

        public StartPageViewModel(){}

        public IStartPageModel Get()
        {
            viewmodel.Heading.Caption = "App-Code.Net";
            viewmodel.SubHeading.Caption = "Hello World";
            return viewmodel;
        }
    }
}

This contains the implementation of the interfaces that we specified earlier. We now need to tell Castle how to resolve these for us. To do this we will create an installer. Create a new class file and call it Installers.cs copy the following code

using Castle.MicroKernel.Registration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOCExample
{
    public class Installers : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            throw new NotImplementedException();
        }
    }
}

To create an installer we first implement the IWindsorInstaller, this gives us the “public void Installer” method that you can see above. Notice that the first parameter is the Windsor container that we will be using. Lets flesh out this installer a little.

using Castle.MicroKernel.Registration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOCExample
{
    public class Installers : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container
                .Register(Component.For<IStartPageModel>().ImplementedBy<StartPageModel>().LifestyleTransient())

                .Register(Component.For<IStartPageViewModel>().ImplementedBy<StartPageViewModel>().LifestyleTransient())

                .Register(Component.For<IHeading>().ImplementedBy<Heading>().LifestyleTransient())

                .Register(Component.For<IShell>().ImplementedBy<Shell>().LifestyleTransient())

                .Register(Component.For<MainWindow>().LifestyleTransient());

        }
    }
}

Here we are using the Fluent interface to register our components with the container. I’ve broken one of the registration lines down a little so that
it makes a little more sense.

container.Register(
    Component
        .For<IStartPageModel>()             //When requesting this interface
        .ImplementedBy<StartPageModel>()    //Respond with this type
        .LifestyleTransient()               //Create a new instance when requested.
);

What we are doing here is telling castle that when we try to resolve the IStartPageModel interface we want it to respond with an instance of the StartPageModel Since we do not have an interface for the MainWindow, you can see that we are specifying the MainWindow type.

We now need to change the App.xaml.cs OnStartup method to tell Castle to install these components. Castle helps us do this by providing a nice simple method.

container.Install(FromAssembly.This());

This just allows castle to look at the current assembly and look for implementations of the IWindsorInstaller interface. Our App.xaml.cs file now looks like this.

using Castle.Windsor;
using Castle.Windsor.Installer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace IOCExample
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// <summary>
    public partial class App : Application
    {
        IWindsorContainer container;
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            container = new WindsorContainer();
            container.Install(FromAssembly.This());
        }
    }
}

Our container is now ready to use. so lets start by resolving our first type. Change your OnStartup method so that it looks like this

    IWindsorContainer container;
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        container = new WindsorContainer();
        container.Install(FromAssembly.This());             // Register

        //resolve our shell to start the application.
        var start = container.Resolve<IShell>();            // Resolve
        start.Run();
        container.Release(start);                           // Release
    }

This is our first resolve. We are telling the container that we want a new instance of the IShell type; this type has the Run() method, and its this that we want to call next. If you look at the implementation of the Shell class you will see that it has a public property of type MainWindow and a public method called Run()

    public class Shell : IShell
    {
        public MainWindow window { get; set; }
        public void Run()
        {
            window.Show();
        }
    }

notice that we are NOT creating an instance of MainWindow anywhere in the application.

start.Run();

When the code executes, Castle will “inject” a new instance of the MainWindow into the property setter of Shell. This is an optional dependency; this means that as long as we specify it as a public property and we are not attempting to access the property inside of the constructor of Shell then the dependency will be wired up automatically. If we required the dependency early on during the instancing of the Shell class we should have created a constructor with a mandatory dependency like this.

public Shell(MainWindow window)
{
    window.Title = "";
}

We wont implement this just now, lets leave the optional dependency in place.

NOTE: If the type or interface exists on the constructor of the type that we are resolving then it is a mandatory dependency; if it exists as a public property of the type that we are resolving then its an optional dependency.

Lets run our application now. You should see that the application starts and the MainWindow opens; its currently blank but we can work on that.

So lets write a little bit more and get the window to display something. Lets start by adding a mandatory dependency to our MainWindow class. Open the MainWindow.xaml.cs file to the code view and change the code behind so that it looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IOCExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// <summary>
    public partial class MainWindow : Window
    {
        public MainWindow(IStartPageViewModel context)
        {
            InitializeComponent();
            this.DataContext = context.Get();
        }
    }
}

Here we have specified a mandatory dependency of IStartPageViewModel called context. We are then using this to set the DataContext of the MainWindow. Looking at the StartPageViewModel’s Get() Method you can see that it populates the Header and SubHeader types and returns an instance of IStartPageViewModel.

Now lets change our MainWindow.xaml code so that we can see something being returned. Open up the MainWindow.xaml file on code view, It should look like this.

<Window x:Class="IOCExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        
    <Grid>
<Window>

Lets make some simple changes. I Wont cover Xaml markup in this tutorial so in this instance please just trust me 🙂 Lets change the in the code above into , your code should now look like this.

<Window x:Class="IOCExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>

    <StackPanel>
<Window>

Lets add a TextBlock so that we can see our data being passed through

Add the following code inside of the tags.

 <TextBlock Text="{Binding Heading.Caption}"  FontSize="22" FontWeight="Bold"></TextBlock>
 <TextBlock Text="{Binding SubHeading.Caption}"></TextBlock>

Your code should now look like this

<Window x:Class="IOCExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
         <TextBlock Text="{Binding Heading.Caption}"  FontSize="22" FontWeight="Bold"></TextBlock>
         <TextBlock Text="{Binding SubHeading.Caption}"></TextBlock>
    <StackPanel>
<Window>

The StackPanel just allows us to place one UI element on top of another, like i said i wont cover the finer points of WPF in this article.

If you run our example you should now see the MainWindow open with the text that was specified in the StartPageViewModel being displayed. Notice that there is only one reference to Resolve in the entire demo, this is how it should be ( register resolve release)

One thing that i didn’t say at the outset of this article was that i would implement the example using the MVVM (Model View ViewModel) design pattern, but that’s exactly what we have built. This article has shown you how to implement a Castle Windsor IOC container, create a very simple model to hold data, a very simple viewmodel to create and populate and a very simple implementation of binding the viewmodel data to controls on the WPF form.

The example shows how to create a good separation of UI and business logic. In the next articles i will cover:-

Download Example

References:

39 Comments

  1. Its such as you read my mind! You seem to understand a lot about this, such as you wrote the e book
    in it or something. I feel that you simply can do with some
    p.c. to pressure the message home a little bit, but other than that,
    that is fantastic blog. An excellent read. I will certainly be back.

  2. Your breakfast can be your foundation for the whole day; so exactly like other
    things, you start with a poor foundation, the structure will never be that great.
    Losing weight and keeping it off is very hard for most people.

    It’s less simple as checking the label and seeking for sugar.

  3. Fantastic beat ! I would like to apprentice while you amend your
    website, how could i subscribe for a weblog site? The account helped me a
    appropriate deal. I were tiny bit familiar of this your broadcast offered
    brilliant clear concept

  4. A percentage of people because of the gamers. The quick downloading sports are convenient in playing casino
    games from all the time to save space. Planet ScienceThe Planet Science games
    cupboard is a true dominations wonders guide gaming pioneer whose
    fun, some phones will send the caller to voicemail.

    This obviously makes a game only when you are playing a mobile phone
    owners, as they are easy to get out of dominations wonders guide it day by day.

  5. Victor worked for Aspen Commercial Security and
    has been continually grateful for the knowledge they have shared with him.
    ‘ Locksmiths can also give genuine suggestions on the kind
    of security systems which should be installed.
    Only the pins and tumblers of the locks are replaced, thereby invalidating
    existing keys.

    Feel free to visit my website; מסגריה בהרצליה | מסגר מסגריות או מסגרים בהרצליה והרצליה פיתוח

  6. Maps, Addresses and Driving Directions to important places
    such as: Local Hospital Emergency Medical or “Walk-In” Clinics; Bank, ATM and Money
    Exchange; Airport, Train Station,and Bus Stations; Post
    Office, Fed – Ex, UPS or other Express Mailing
    Businesses; Grocery Stores, Butcher, Baker, Liquor Stores, or
    other Essential Stores; Internet Café or Business
    Center; Recommended Restaurants, Cafes, Clubs, or Thoroughfares; Local Places of Worship
    with phone numbers. Usually a security code is used to open these kinds of locks.
    Are you looking for an effective way to protect your family and your home.

    Look at my page מסגריות

  7. We should be cautious even though picking a locksmith, as we
    will need a skilled that will be ready to securely safe our treasured items.
    It’s possible you’ll even search for evaluations online.
    A locksmith Apache service provider will be able
    to help you install a wide variety of locks and
    security devices that can improve the security of your house.

    Also visit my homepage :: מסגרים בפתח תקווה

  8. Another option to have a secure home is to change your lock rather than install a new.
    • Don’t forget to check its compatibility with
    your building structure and the ability of the system to
    deliver a good sound quality which depends on the
    structure of your home. Make sure you clean your face thoroughly before
    moisturizing.

    Feel free to visit my web site מסגרים

  9. This church, regarded with profound respect by the
    islanders, occupies the exact location where the first chapel
    on island was built. Also make sure the “USB Type A to mini-B “cable
    length is long enough to connect your USB devices to the hub.
    There are many medications and remedies that the physician will suggest.

    my weblog; Seilzug

  10. Hello would you mind sharing which blog platform you’re working with?
    I’m planning to start my own blog in the near future but I’m having a
    tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your layout seems different then most
    blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!

    Here is my web site – מנעולן גנב בהוד השרון

  11. Maximum amount of money in the pool is taken away by the jackpot winner.
    t want to simply end up going in for online slots that you are not particularly going to benefit
    from. I made a bait dip that included the liquids previously mentioned and added some Liquid Mussel
    Extract and Liquid Bloodworm Extract and fine sea salt too.

  12. Practical ideas . I loved the insight ! Does anyone know where my business could possibly get ahold of a template TX Medicaid Provider Enrollment Application example to complete ?

  13. Fascinating blog! Is your theme custom made or did you download it from somewhere?

    A theme like yours with a few simple tweeks would really make
    my blog shine. Please let me know where you got your design. With thanks

  14. Hi blogger, i must say you have hi quality articles here.
    Your blog can go viral. You need initial traffic only. How to get it?

    Search for; Mertiso’s tips go viral

  15. I have noticed that your website needs some fresh posts.
    Writing manually takes a lot of time, but there is tool for this boring task, search for: Wrastain’s
    tools for content

  16. I have noticed you don’t monetize your website, don’t waste your traffic,
    you can earn additional cash every month because you’ve got
    high quality content. If you want to know how to make extra money, search for: best adsense alternative Wrastain’s tools

  17. Szukasz wartościowego źródła informacji dot. kredytów pozabankowych? Ostatnio kredyt bez bik jest wśród mieszkańców Polski niesamowicie powszechny, jednak niestety nie wszystkie oferty są fair – głównie po to otworzyliśmy ową witrynę internetową, aby nareszcie polscy internauci mogli przekonać się, który kredyt bez zaświadczeń jest godny uwagi pod każdym względem. Całkiem często umieszczamy swoje poglądy na temat nowych ofert pożyczkowych, a więc wystarczy zaglądać akurat do nas, aby wiedzieć jaki kredyt gotówkowy jest korzystnie oprocentowany, w zupełności pozbawiony ukrytych opłat, etc. [url=https://bezbiku.ebrokerpartner.pl]kredyt bez bik[/url] [url=https://bezbiku.ebrokerpartner.pl]pozyczka bez zaswiadczen[/url] [url=https://bezbiku.ebrokerpartner.pl]pozyczka gotowkowa[/url] Brak zatrudnienia, zadłużenie czy kiepska płaca nie są kłopotem dla planujących wziąć kredyt gotówkowy – a przynajmniej mówimy w tym momencie o odwiedzających naszą stronę. Rzeczywistość jest taka, że zamieściliśmy na stronie rady, które sprawiają, iż natrafienie na kredyt bez zaświadczeń, oczywiście całkiem nisko oprocentowany, to drobnostka. Jednakże serwis nie posiada tylko i wyłącznie czysto informacyjnego charakteru – również można po prostu załatwić sobie właśnie na nim kredyt bez bik.

    Pewnie chciałbyś wreszcie pozyskać taki kredyt gotówkowy, który sprawi, że kupisz sobie powiedzmy pralkę albo opłacisz wynajem mieszkania, lecz później nie będziesz miał żadnych przykrości. No cóż, od czego jest zatem otworzony przez nas serwis? No co jak co, ale autentycznie nikt kto rozważnie podejście do lektury treści w serwisie nie będzie mieć żadnych wątpliwości odnośnie tego, który kredyt bez bik, a właśnie o kredytach bez zaświadczeń mowa, jest prawdziwym strzałem w dziesiątkę. Naturalnie wszystkie porady zostały napisane w taki sposób, że definitywnie każdy pojmie o co się rozchodzi. W końcu kredyt bez zaświadczeń jak najbardziej może być przystępny. Pod każdym względem.

    Wartościowe kompendium porad dla tego internauty, który kompletnie nie wie, który kredyt bez bik na tę chwilę jest w ścisłej czołówce. Ciężko zazwyczaj wybrać kredytodawcę, ale po lekturze otworzonego przez nas wortalu nareszcie wszystko będzie już jasne. Żywimy ogromną nadzieję, że kredyt gotówkowy w istocie jest tym czymś na czym świetnie się znamy – reakcje użytkowników są zawsze pozytywne. Z wielką chęcią odpowiemy na wszelakie zapytania jeśli wchodzi w grę kredyt bez zaświadczeń, regularnie aktualizujemy stronę, a więc wszyscy kredytobiorcy powinni być zadowoleni.

  18. A Biological Masterpiece, But Subject to Many Ills
    The human foot is a biological masterpiece. Its strong, flexible, and functional design enables it to do its job well and without complaint—if you take care of it and don’t take it for granted.
    healthThe foot can be compared to a finely tuned race car, or a space shuttle, vehicles whose function dictates their design and structure. And like them, the human foot is complex, containing within its relatively small size 26 bones (the two feet contain a quarter of all the bones in the body), 33 joints, and a network of more than 100 tendons, muscles, and ligaments, to say nothing of blood vessels and nerves.
    [url=https://www.cialissansordonnancefr24.com/effets-secondaires-cialis-generique/]https://www.cialissansordonnancefr24.com/effets-secondaires-cialis-generique/[/url]

Comments are closed.