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.
当我解析ComponentA时,Castle正确地注入ComponentB和ComponentC。
However, if there is a problem instantiating ComponentB
, it swallows the exception, resulting in delayed errors (NullReferenceException).
但是,如果在实例化ComponentB时出现问题,则会吞下该异常,从而导致延迟错误(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?
我理解两种方法之间的区别,但是当注入属性出现问题时,是否可能使其失败(或者至少记录完整的异常)?
2 个解决方案
#1
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.
根据Mauricio对Phil链接问题的回答,我创建了一个StrictComponentActivator,即使依赖项是可选的,也不会吞下异常。
Works as expected.
按预期工作。
#2
0
I believe this is expected behavior, and AFAIK there is no way around it.
我相信这是预期的行为,而AFAIK没有办法绕过它。
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.
一个选项可能是使用ComponentB的私有成员设置为默认实现(如果需要,则在访问时抛出异常),但如果解析成功则被容器覆盖。
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
温莎城堡奇怪的行为与财产注入和工厂方法
#1
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.
根据Mauricio对Phil链接问题的回答,我创建了一个StrictComponentActivator,即使依赖项是可选的,也不会吞下异常。
Works as expected.
按预期工作。
#2
0
I believe this is expected behavior, and AFAIK there is no way around it.
我相信这是预期的行为,而AFAIK没有办法绕过它。
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.
一个选项可能是使用ComponentB的私有成员设置为默认实现(如果需要,则在访问时抛出异常),但如果解析成功则被容器覆盖。
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
温莎城堡奇怪的行为与财产注入和工厂方法