castle-windsor

Getting started with castle-windsor

Remarks#

Castle Windsor is a mature Inversion of Control container available for .NET and Silverlight.

  • The current release version is 3.3.0, released in May 2014. Refer to the links on the right to download it from GitHub or NuGet.
  • Castle Core version 4.0.0 beta was released in July 2016.

To Castle’s official website

To Castle’s Documentation Pages

Installation

Castle Windsor is available via NuGet

  1. Use the “Manage NuGet Packages” and search for “castle windsor”

  2. Use Package Manager Console to execute:

    Install-Package Castle.Windsor

Now you can use it to handle dependencies in your project.

var container = new WindsorContainer(); // create instance of the container
container.Register(Component.For<IService>().ImplementedBy<Service>()); // register depndency
var service = container.Resolve<IService>(); // resolve with Resolve method

See official documentation for more details.

Castle.Windsor package depends on Castle.Core package and it will install it too

Hello World - Castle Windsor

class Program
{
    static void Main(string[] args)
    {
        //Initialize a new container
        WindsorContainer container = new WindsorContainer();

        //Register IService with a specific implementation and supply its dependencies
        container.Register(Component.For<IService>()
                                    .ImplementedBy<SomeService>()
                                    .DependsOn(Dependency.OnValue("dependency", "I am Castle Windsor")));

        //Request the IService from the container
        var service = container.Resolve<IService>();
        
        //Will print to console: "Hello World! I am Castle Windsor
        service.Foo();
}

Services:

public interface IService
{
    void Foo();
}

public class SomeService : IService
{
    public SomeService(string dependency)
    {
        _dependency = dependency;
    }

    public void Foo()
    {
        Console.WriteLine($"Hello World! {_dependency}");
    }

    private string _dependency;
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow