Kei*_*oom 10 castle-windsor circular-dependency inversion-of-control unity-container
是否可以将Unity配置为检测循环引用或拦截类型解析器以显示某些调试信息?
这里有几个相互依赖的接口和类
public interface IThing1 { }
public class Thing1 : IThing1
{
private IThing2 _thing2;
public Thing1(IThing2 thing2)
{
_thing2 = thing2;
}
}
public interface IThing2 { }
public class Thing2 : IThing2
{
private IThing1 _thing1;
public Thing2(IThing1 thing1)
{
_thing1 = thing1;
}
}
Run Code Online (Sandbox Code Playgroud)
如果在Castle Windsor中配置了这两种类型,它将抛出异常并提供一些调试信息以查找循环引用:
Castle.MicroKernel.CircularDependencyException: Dependency cycle has been detected when trying to resolve component 'CircularIoC.Thing1'.
The resolution tree that resulted in the cycle is the following:
Component 'CircularIoC.Thing1' resolved as dependency of
component 'CircularIoC.Thing2' resolved as dependency of
component 'CircularIoC.Thing1' which is the root component being resolved.
Run Code Online (Sandbox Code Playgroud)
如果Unity配置为解决这些类型,请执行此操作
private static void ResolveWithUnity()
{
var container = new UnityContainer();
container.RegisterType<IThing1, Thing1>();
container.RegisterType<IThing2, Thing2>();
var thing = container.Resolve<IThing1>();
container.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
对container.Resolve <>的调用将导致StackOverflowException.
这是记录在案的行为,但是有一些更有用的信息会很好.是否有任何自定义可以提供有关循环引用的更多信息?
或者有没有办法挂钩到类型解析器进程发出一些调试信息?我正在考虑装饰主类型解析器以输出正在解析的类型的名称.这将提供一些反馈和指向导致循环引用的依赖项的指针.
虽然我知道改用不同的IoC可以解决问题,但不幸的是这不是一个选择.
遗憾的是 Unity 不支持这个(非常重要的)功能。如果您愿意全力以赴,您可以使用一些苦力来实现智能装饰器。
您需要的是覆盖所有注册方法并构建和更新依赖关系的数据结构(依赖关系图)。然后编写一个执行DFS的方法来检测循环依赖项,您可以将其用作注册过程的终结器,它将检测预解析是否可能存在循环依赖项,或者在每次解析时使用它来请求特定类型。
正如你所看到的,工作量很大......
另一种选择是用装饰器包装解析方法并捕获 StackOverflowException ,分析它以确保它是解析过程的结果,并构建适当的循环依赖异常。
| 归档时间: |
|
| 查看次数: |
1899 次 |
| 最近记录: |