我有两个范围,一个嵌套在另一个范围内。当我解析特定服务时,我希望在一个根作用域中解析一个组件,在子作用域中解析另一个组件。这样做有简单的方法吗?
我设法使用工厂类来确定当前范围是什么,然后返回适当的实例:
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
{
}
这种方法存在许多问题:
Autofac.Core.Lifetime.LifetimeScope
并检查ParentLifetimeScope
属性来解决此问题,但这可能不是特别安全的事情。答案 0 :(得分:9)
您可以在根容器中将FooInParentScope注册为SingleInstance。在创建内部生命周期时,为FooInChildScope添加注册为SingleInstance(覆盖注册)。
builder.RegisterType<FooInParentScope>().As<IFoo>.SingleInstance();
var container = builder.Build();
var childScope = container.BeginLifetimeScope(innerBuilder =>
{
// override registration for IFoo in child lifetime scope:
innerBuilder.RegisterType<FooInChildScope>().As<IFoo>().SingleInstance();
});
FooInParentScope fooInParentScope = (FooInParentScope) container.Resolve<IFoo>();
FooInChildScope fooInChildScope = (FooInChildScope) childScope.Resolve<IFoo>();