views:

103

answers:

3

How can I allow one of my string parameters to be an empty string?

I get this error when I try either nothing or a single space (names changed):

Could not resolve non-optional dependency for 'test.User' (MyNamespace.MyObject). Parameter 'userName' type 'System.String'

+2  A: 
container.Register(
   Component.For<Foo>()
      .DependsOn(new
      {
         someString = string.Empty
      }));

but first of all, why do you want to set that dependency to empty string? It does feel like hacking to me.

Krzysztof Koźmic
I was typing up a reason why I wanted to do this only to realize I could just add another constructor that excluded the parameters I wanted to leave empty... +1 to you for calling me out on the hacking.
Austin Salonen
yes, additional .ctor that explicitly excludes the parameter is usually the preferred solution.
Krzysztof Koźmic
+1  A: 

Turns out it's much easier, and likely more correct, to add a constructor that doesn't take the parameter(s) you want to leave blank.

Austin Salonen
A: 

What if there is already a default value, which is null, or some other non-empty string? One solution is to create a component:

<component id="emptyString" type="System.String, mscorlib" />

and then use it in your parameters node:

<parameters> <someStringParameter>${emptyString}</someStringParameter> </parameters>

But it seems like there ought to be a simpler way.

phoog
Won't work. You can't use `string` as a component. It does not make sense and Windsor won't let you.
Krzysztof Koźmic
Why do you say it won't work? I did it before I posted, and the associated parameter value in the constructor was indeed the empty string. Is it version dependent? I am using Castle.Core 1.2.0.0, Castle.MicroKernel 2.1.0.0, Castle Windsor 2.1.0.0.Further, and more importantly, if it doesn't make sense, what is the better solution?Thanks.
phoog

related questions