Search code examples
castle-windsorwindsor-3.0

Basic Windsor Constructor Injection


I am new to Windsor and am trying to implement the most basic constructor injection. Apparently the API has changed so much over the recent versions that the documentation that is for the current version seems to assume you already know how to do it, and the documentation for the old versions is outdated.

I have a simple test component:

public class ConstructorInjectedComponent
{   
    public IMyComponent Component { get; set; }

    public ConstructorInjectedComponent(IMyComponent component)
    {
        Component = component;
    }
}

There is a simple implementation of IMyComponent:

public class AMyComponent : IMyComponent
{
    public string Name { get; set; }

    public AMyComponent()
    {
        Name = Guid.NewGuid().ToString("N");
    }
}

And I want to somehow register my types with Windsor such that I can get back an instance of ConstructorInjectedComponent that contains an instance of its dependency: IMyComponent.

I've register AMyComponent like so:

_container.Register(Component.For(typeof(AMyComponent)));

I've register ConstructorInjectedComponent like this:

_container.Register(Component.For(typeof(ConstructorInjectedComponent)));

and tried to resolve it with

_container.Resolve(typeof(ConstructorInjectedComponent));

But that fails with "can't create component ConstructorInjectedComponent because it has dependencies which need to be satisfied.

so I try to pass in an IDictionary of dependencies for the ConstructorInjectedComponent ... and this is where the documentation fails me.

I have no idea how to define that dictionary. I can find no documentation which explains it. I've tried this:

var d = new Dictionary<string, string>() {{"IMyComponent", "AMyComponent"}};
_container.Register(Component.For(typeof(ConstructorInjectedComponent))
                    .DependsOn(dependencies));

But that fails with the same "has dependencies that need to be resolved" error.

What am I doing wrong?


Solution

  • First it's crucial to make sure you understand the basic concepts, namely what a component is, what a service is, and what a dependency is.

    The documentation about it is quite good.

    The documentation about how to use registration API should help you get going.

    The tl;dr asnwer is: since ConstructorInjectedComponent depends on IMyComponent make sure you register AMyComponent to expose IMyComponent as a service.

    _container.Register(Component.For<IMyComponent>().ImplementedBy<AMyComponent>());