【发布时间】:2023-03-28 11:18:01
【问题描述】:
所以,我正在尝试解决一个我确信其他人已经遇到过的问题。基本上,我希望调用我的 IoC 容器以递归方式解决依赖关系,但也可能执行一些自定义代码以根据一组预定义的标准更改结果。这很模糊,所以让我举个例子:
假设我有一个这样的控制器:
public class SampleController : Controller
{
protected SampleType _sampleType = null;
public SampleController(SampleType sampleType)
{
_sampleType = sampleType;
}
}
我也有这个控制器的一些测试版本(比如说我重构了它,我想通过 AB 测试它的曝光确保它不会在 prod 中严重损坏):
public class SampleController_V2 : SampleController
{
protected SampleType _sampleType = null;
protected AnotherType _anotherType = null;
public SampleController_V2(SampleType sampleType, AnotherType anotherType)
{
_sampleType = sampleType;
_anotherType = anotherType;
}
}
我已扩展 DefaultControllerFactory 以在创建控制器时使用 Unity。这一切都很好。现在,我想做的是,如果要解决问题,它提供了对层次结构中的任何特定类型进行 AB 测试的能力。这适用于顶层,但不适用于子元素,因为它在对象图中递归。
现在,它将选择合适的控制器来解析并为其提供依赖项。但是,我似乎无法拦截对依赖项的各个调用以也 AB 测试这些。我可以通过数据库配置定义一个测试,然后让 IOC 容器根据标准来解决它。示例:
SessionIds that start with the letter 'a': SampleController_V2
Everyone Else : SampleController
UserIds ending in 9 : SampleType_V2
Everyone Else : SampleType
这一切都适用于顶级项目。但是,对_unityContainer.Resolve(type) 的调用似乎不是递归调用;我希望能够在尝试解析类型时将该代码注入任何点:
-> Attempt to Resolve SampleController
-> Test Code Tells Us to use _V2 if possible.
-> Attempt to Resolve SampleType
-> Test Code tells us to use the _V1 if possible.
-> Resolves SampleType_V1
-> Attempt to Resolve AnotherType
-> No Test Defined, Use the Default
-> Resolves AnotherType
-> Resolves SampleController_V2 (passing SampleType_V1 as the dependency and then AnotherType as the other dependency)
翻看网上的一些文章,听起来好像需要使用某种 Unity 拦截器,但这几乎就像我正在编写自己的 IoC 容器,并内置了某种测试架构。
希望在我痛苦地寻找构造函数然后递归地解析每种类型之前,有人对如何做到这一点有一个好主意。
编辑:所以通过递归检查每个依赖项的构造函数参数来创建自己的注入实际上并没有那么可怕,但我认为如果我为自己的自定义丢弃 Unity,老板们可能会有点不安解决方案。
【问题讨论】:
-
我可能误会了。您想根据输入的测试数据解析不同的对象图吗?我不确定您为什么要这样做 - 当我使用容器进行测试时,我会尽量让对象图尽可能接近生产环境。
-
为特定对象提供AB测试。例如:假设我有一个 EmailSender 类。它确实是 X。但是,我想测试一个重写的 EmailSender 类。我让 IOC 容器在它的位置解析一个 EmailSender_V2 类,它会做 Y。说它可能是性能密集型的;我想慢慢介绍它,看看它是否对网站产生了负面影响。然后,我可以提高到 100%,并在将来将该代码移至基本版本,而无需修改控制版本。然后大多数用户获得相同的体验;一些用户在测试时获得了增强的体验。
标签: c# asp.net-mvc recursion unity-container ab-testing