3

Consider the following class:

public class ComponentA
{
    public ComponentB ComponentB { get; set; }

    public ComponentA(ComponentC componentC) { ... }
}

When I resolve a ComponentA, Castle injects both ComponentB and ComponentC correctly.

However, if there is a problem instantiating ComponentB, it swallows the exception, resulting in delayed errors (NullReferenceException).

I understand the difference between both approaches, but is it possible to make it fail (or at least log the full exception) when there is a problem with an injected property?

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154

2 Answers2

1

Based on Mauricio's answer to the question linked by Phil, I created a StrictComponentActivator which does not swallow the exception even if the dependency is optional.

Works as expected.

Community
  • 1
  • 1
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
0

I believe this is expected behavior, and AFAIK there is no way around it.

An option might be to use a private member for ComponentB that gets set to a default implementation (that throws an exception when accessed if that's what is needed), but gets overridden by the container if resolution is successful.

private ComponentB _b = new ExceptionThrowingComponentB();

public ComponentB B
{
   get { return _b; }
   set { _b = value; }
} 

As svick noted: not a good solution.

Edit: I'm not sure I understand what all is involved, but it sounds like you can change this behavior:

Castle Windsor strange behaviour wth property injection and factory method

Community
  • 1
  • 1
Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
  • How is exception throwing implementation different from `null`, that always throws an exception when trying to use it too? – svick Jul 18 '11 at 23:21
  • Eh, you're right, there really isn't. I started with a default/no-op implementation (which is the way I usualy do it) and then realized he wanted an exception thrown. – Phil Sandler Jul 18 '11 at 23:44