C# 简单注入器:在运行时替换注册的类型

C# 简单注入器:在运行时替换注册的类型,c#,simple-injector,C#,Simple Injector,在Simple Injector中是否有任何方法可以在运行时替换结构映射中的一种类型的默认值,即containter.Injector()?我借用使用结构图如下 var container = new Container(x => { x.For<IFoo>().Use<AFoo>(); }); container.GetInstance<IFoo>().ShouldBeOfType<AFoo>(); container.Configure(

在Simple Injector中是否有任何方法可以在运行时替换结构映射中的一种类型的默认值,即
containter.Injector()
?我借用使用结构图如下

var container = new Container(x => { x.For<IFoo>().Use<AFoo>(); });
container.GetInstance<IFoo>().ShouldBeOfType<AFoo>();
container.Configure(x => x.For<IFoo>().Use<BFoo>());

// The default of IFoo is now different
container.GetInstance<IFoo>().ShouldBeOfType<BFoo>();

// or use the Inject method that's just syntactical
// sugar for replacing the default of one type at a time
container.Inject<IFoo>(new CFoo());

container.GetInstance<IFoo>().ShouldBeOfType<CFoo>();
我的应用程序没有问题。成功了。但是在我的单元测试中(没有模拟的真实本地DB),我想用登录用户替换IIdentity。我用了结构图,效果很好。现在我不知道如何使它与简单的喷油器一起工作

但是在我的单元测试中(没有模拟的真实本地DB),我想用登录用户替换IIdentity

对于单元测试,您完全可以使用不同的注册替换真实的
IIdentity
注册。您只需在从容器解析之前执行此操作


这意味着每个集成测试(我说“集成”,因为单元测试不应该使用DI容器)都应该有自己的
Container
实例。其次,为了能够覆盖现有注册,您必须设置
container.Options.AllowOverridingRegistrations
。有关更多信息,请阅读。

为什么要在运行时替换实例?我猜您也阅读了代码段下面的段落?“首先,关于此功能的最好建议是不要在根容器上的测试场景之外使用它。”@Steven我用当前上下文更新了我的问题谢谢你的回答。实际上是集成测试。在问这个问题之前,我考虑过这个解决方案。我只想找到另一种更清洁的解决方案,而不用碰任何容器。
// bypass verify was removed for short
_container.Register<HttpContextBase>(() => new HttpContextWrapper(HttpContext.Current)); 
_container.Register(() => _container.GetInstance<HttpContextBase>().User.Identity);
public class MyService : IMyService
{
    public MyService(IIdentity identity)
    {
        //...
    }
    //...
}