Diego Mijelshon
Diego Mijelshon

Reputation: 52745

Throwing an exception when failing to resolve a dependency

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?

Upvotes: 3

Views: 2109

Answers (2)

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

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.

Upvotes: 1

Phil Sandler
Phil Sandler

Reputation: 28046

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

Upvotes: 0

Related Questions