私には2つのスコープがあり、一方はもう一方の中にネストされています。特定のサービスを解決するとき、1つのコンポーネントを1つのルートスコープで解決し、別のコンポーネントを子スコープで解決したいと思います。これを行う簡単な方法はありますか?
現在のスコープが何であるかを決定するファクトリクラスを使用して何かを機能させ、適切なインスタンスを返すことができました。
IContainer BuildContainer()
{
var builder = new ContainerBuilder();
// ...
builder.RegisterType<FooInParentScope>().AsSelf();
builder.RegisterType<FooInChildScope>().AsSelf();
builder.RegisterType<FooFactory>().AsImplementedInterfaces();
builder.Register<IFoo>(c => c.Resolve<IFooFactory>().GetFoo()).InstancePerLifetimeScope();
// ...
}
class FooFactory : IFooFactory
{
private readonly ILifetimeScope m_scope;
public FooFactory(ILifetimeScope scope)
{
m_scope = scope;
}
public IFoo GetFoo()
{
if (m_scope.Tag == "ParentScope")
return m_scope.Resolve<FooInParentScope>();
else
return m_scope.Resolve<FooInChildScope>();
}
}
class FooInParentScope : IFoo
{
}
class FooInChildScope : IFoo
{
}
このアプローチにはいくつかの問題があります。
- クラスを追加する必要があります(または2-IFooFactoryが本当に必要かどうかはわかりません)
- 上記のコードは、ParentScopeにネストされている他のスコープには対応していません。
Autofac.Core.Lifetime.LifetimeScope
スコープをキャストしてプロパティを調べることでこれを修正できますParentLifetimeScope
が、それはおそらく特に安全なことではありません。