Search code examples
.netdependency-injectioncastle-windsor

Castle Windsor 3 with constructor argument as string


I have never used Windsor before but have used other DI frameworks, and I have got a rather strange issue at the moment.

I have a factory class which takes a string in its constructor, however whenever I try and resolve that object I get an exception saying:

Handler for System.String was not found.

<Message>Handler for System.String was not found.</Message>
<StackTrace>at Castle.MicroKernel.Resolvers.DefaultDependencyResolver
     .TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context) 
     in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 403
at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ComponentModel model, DependencyModel dependency) in d:\60b7fa65294e7792\src\Castle.Windsor\MicroKernel\Resolvers\DefaultDependencyResolver.cs:line 270</StackTrace>
<Type>Castle.MicroKernel.Handlers.HandlerException</Type>
</InnerException>
<Message>Missing dependency.
Component SomeExampleFactory has a dependency on System.String, which could not be 
resolved.
Make sure the dependency is correctly registered in the container as a service, or 
provided as inline argument.</Message>

The class looks something like:

public interface IDummyFactory
{
    void DoSomething();
}

public class DummyFactory : IDummyFactory
{
    private string someString;

    public DummyFactory(string someConstructorArg)
    {
        someString = someConstructorArg;
    }
}

With DI setup below:

var someString = "some constructor arg";
_container.Register(Component.For<IDummyFactory>()
                             .ImplementedBy<DummyFactory>()
                             .DependsOn(someString));

I am assuming it is trying to do some sort of casting or formatting that is causing it to bomb out, but as the type itself is a string, and the variable being passed in a string... it may even be a case that it is trying to map the type of that variable rather than the variable content, but I do not know enough about the DI framework and the documentation around this area


Solution

  • Try calling the overload of DependsOn which takes an IDictionary of Key/Value pairs to specify dependencies:

    _container.Register(
        Component.For<IDummyFactory>()
            .ImplementedBy<DummyFactory>()
            .DependsOn(new Hashtable 
            { 
                { "someConstructorArg", "some constructor arg" }
            }));