How to setup more complicated (IoC like) registration in AutoFixture

[亡魂溺海] 提交于 2019-12-01 22:33:41

The general approach looks sound, but you should add the ContainerSpecimenBuilder to ResidueCollectors instead of to Customizations:

fixture.ResidueCollectors.Add(new ContainerSpecimenBuilder(containerBuilder.Build()));

AutoMoqCustomization also adds a node to ResidueCollectors, so you may need to experiment a bit with the specific ordering to figure out exactly how to make it behave like you want it to behave. The ordering matters.

For more information about the difference between Customizations and ResidueCollectors, see the AutoFixture architecture documentation.


A slightly simpler (and safer?) implementation of ContainerSpecimenBuilder could be just handling requests for Type instances directly, instead of for SeededRequest, as almost all SeededRequest values are relayed to requests for Type objects anyway:

internal class ContainerSpecimenBuilder : ISpecimenBuilder
{
    private readonly IContainer container;

    public ContainerSpecimenBuilder(IContainer container)
    {
        this.container = container;
    }

    public object Create(object request, ISpecimenContext context)
    {
        var t = request as Type;

        if (t == null)
            return new NoSpecimen(request);

        var result = this.container.ResolveOptional(t);
        return result ?? new NoSpecimen(request);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!