Allow optional (null) property injection in Castle Windsor via factory method?
Asked Answered
M

1

8

I've registered a component

container.Register(Component.For<XType>()
 .LifeStyle.Is(LifestyleType.Transient)
 .UsingFactoryMethod(SomeMethod));

and am currently using this for property injection on my ASP.NET MVC controllers. However - my current problem is that SomeMethod can return null sometimes. Castle is not all too happy about this and complains about a null instance.

Is there a neat way to configure Windsor to allow this component to be null? I've been exploring the docs but haven't found a way to do it.

Thanks.

Mnemosyne answered 26/8, 2010 at 8:11 Comment(3)
Does your clients handle null component references? You can put null-handling code in a default implementation and create it instead of returning nullAgnusago
I am using the NullObject pattern as a temporary solution. Another option could be wrapping it in a another component which only returned the null / non-null value - but it seems kind of clunky.Mnemosyne
It is also contructor injected in some places (where it is guaranteed not to be null though) - and the way our controllers are registered, using dynamic parameters isn't really viable - but I'll accept your answer since it's correct :-)Mnemosyne
A
6

No, there's no way to pass null via Windsor.

If the component is null, than it obviously can not be used, so it would be pointless if that would be possible anyway.

If you're using this component only as a property on some other component, I think it would be better to just pass it as DynamicParameter. Windsor will then just ignore it if it's null.

Akkad answered 26/8, 2010 at 9:26 Comment(2)
It is a transient dependency that is sometimes null - usually it has a meaningful value - the factory method is called for each request. I can't see how that is entirely pointless.Mnemosyne
I agree that it would be useful to allow nulls. It would be a good way of inverting static objects, e.g. in WCF, ServiceSecurityContext.Current. However, that can of course be null if the user is not authenticated. A null object pattern is the best way round.Hydrometallurgy

© 2022 - 2024 — McMap. All rights reserved.