以下のような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>())