我有一个 Autofac 模块如下
public class ServiceInjector:Module
{
protected override void Load(ContainerBuilder builder)
{
// many registrations and type looking up here
...
// One of the registration, say t which is found
// in above looking, is a resource consuming type
builder.RegisterType(t).As<ITimeConsume>();
// ...
}
}
此模块用于 ServiceClass:
public class ServiceClass
{
static IContainer _ioc;
public ServiceClass()
{
var builder = new ContainerBuilder();
builder.RegisterModule<ServiceInjector>();
_ioc = builder.Build();
}
public void InvokeService()
{
using(var scope = _ioc.BeginLifetimeScope())
{
ITimeConsume obj = scope.Resolve<ITimeConsume>(...);
var result = obj.DoTimeConsumingJob(...);
// do something about result here ...
}
}
}
我的问题是:如何通过模拟(Moq) ITimeConsume 类来测试 ServiceClass ?在这里,我尝试在下面编写一个测试:
public void Test()
{
Mock<ITimeConsume> moc = GetMockObj(...);
// How can I inject moc.Object into ServiceInjector module,
// so that ServiceClass can use this mock object ?
}
如果这种方式不可能,那么模拟也可以注入的耗时类的更好设计是什么?
**
更新:
** 感谢@dubs 和@OldFox 提示。我认为关键是 Autofac 注入器应该在外部初始化而不是内部控制。因此,我利用 Autofac.ILifetimeScope 的“ On Fly ”构建功能并使用 LifeTime 范围参数设计 ServiceClass 构造函数。通过这种设计,我可以在单元测试中即时注册任何服务,如下例所示:
using(var scope = Ioc.BeginLifetimeScope(
builder => builder.RegisterInstance(mockObject).As<ITimeConsume>())