在我的测试中,我设置了一个autofac容器,它返回一些真正的实现和一些模拟(DB,外部系统)。
问题是每次测试后我都会处理容器并创建一个新容器:
Autofac.IContainer.Dispose()
和Container = builder.Build();
已经注册的实例仍在那里。
如何重置容器以便它再次像'new'一样?
我想要做的是 - 我想用另一个替换一个模拟的实例。它被注册为Singleton。
----编辑
感谢您的回答。我决定添加更多代码并描述我实际想要实现的目标。但这实际上是另一个话题(已经回答的问题 - 单元测试CQRS)。
我的应用包含静态IContainer属性:
public static IContainer Container { get; private set; }
在每次测试执行后,我通过调用这两个方法再次创建它:
public static ContainerBuilder Compose(IEnumerable<DependencyProvider> dependencyProviders)
{
var collection = dependencyProviders as List<DependencyProvider> ?? dependencyProviders.ToList();
var included = new HashSet<DependencyProvider>(collection);
var includedTypes = new HashSet<Type>(collection.Select(x => x.GetType()));
var currentWorkingSet = new List<DependencyProvider>(collection);
while (true)
{
var candidates = currentWorkingSet.SelectMany(x => x.GetDependencies());
var typesToBeAdded = candidates.Where(x => !includedTypes.Contains(x)).Distinct().ToList();
if (typesToBeAdded.Any() == false)
break;
currentWorkingSet.Clear();
foreach (var type in typesToBeAdded)
{
includedTypes.Add(type);
var instance = CreateInstance(type);
included.Add(instance);
currentWorkingSet.Add(instance);
}
}
return BuildContainer(included);
}
和
TestDependencyProvider dependencyProvider = new TestDependencyProvider()
var builder = Compose(new[] { dependencyProvider });
Container = builder.Build();
为每个测试创建TestDependencyProvider
并包含moqed实例。它注册了这些模拟,x.GetDependencies()
使用原始容器注册,即container.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IAggregateBusinessRuleForEvent<,>));
我最感兴趣的类型是IAggregateBusinessRuleForEvent<,>)
的实现之一。
public class RuleA: IAggregateBusinessRuleForEvent<AEvent, Something>
{
private readonly IDependency _dependency;
public RejectCompanyNameRule(IDependency dependency)
{
_dependency = dependency;
}
}
因此,即使我再次创建此容器,RuleA
仍然存在且我的所有测试都使用相同的_dependency
实例:/
为什么代码看起来看起来仍然不清楚,我试图通过添加测试来理解它......
-------编辑2
根据Jimmy的建议,我使用Update
我
public interface IExample<T>
{
void Hello();
}
public interface IExampleDependecy
{
void SaySomething();
}
public class Example : IExample<string>
{
private IExampleDependecy _dependecy;
public Example(IExampleDependecy dependecy)
{
_dependecy = dependecy;
}
public void Hello()
{
Console.WriteLine("Hello");
_dependecy.SaySomething();
}
}
[TestMethod]
public void T()
{
// first test
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IExample<>));
var mockA = new Moq.Mock<IExampleDependecy>();
mockA.Setup(d => d.SaySomething()).Callback(() => Console.WriteLine("A"));
builder.RegisterInstance(mockA.Object).SingleInstance();
var container = builder.Build();
var sample1 = container.Resolve<IExample<string>>();
sample1.Hello();
// new test using same container
var updater = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IExample<>));
var mockB = new Moq.Mock<IExampleDependecy>();
mockB.Setup(d => d.SaySomething()).Callback(() => Console.WriteLine("B"));
builder.RegisterInstance(mockB.Object).SingleInstance();
updater.Update(container); // overwrites existing registrations
var sample2 = container.Resolve<IExample<string>>();
sample2.Hello();
}
结果是:
Hello
A
Hello
A
答案 0 :(得分:1)
默认情况下,Autofac会覆盖之前的注册以及后续注册。这意味着除了使用新实例更新容器外,您不必执行任何特殊操作:
var builder = new ContainerBuilder();
builder.RegisterInstance(new Sample("A")).SingleInstance();
var container = builder.Build();
var sample = container.Resolve<Sample>();
// do your test
...
// new test using same container
var updater = new ContainerBuilder();
updater.RegisterInstance(new Sample("B")).SingleInstance();
updater.Update(container); // overwrites existing registrations
var sample = container.Resolve<Sample>(); // returns "B"