我有两个范围,一个嵌套在另一个范围内.当我解析特定服务时,我希望在一个根作用域中解析一个组件,在子作用域中解析另一个组件.有这么简单的方法吗?
我设法使用工厂类来确定当前范围是什么,然后返回适当的实例:
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
{
}
Run Code Online (Sandbox Code Playgroud)
这种方法存在许多问题:
Autofac.Core.Lifetime.LifetimeScope和检查ParentLifetimeScope属性来解决这个问题,但这可能不是特别安全的事情.