依赖链中的Autofac更改实例

时间:2015-12-23 11:03:29

标签: c# dependency-injection autofac

我的层次结构看起来很像:

public class SomeBaseClass { }

public class Child1: SomeBaseClass { }

public class Child2: SomeBaseClass { }


//Objects hierarchy

public class A
{
  public A(B b, SomeBaseClass sbc) { }
}

public class B
{
  public B(C c) { }
}

public class C
{
  public B(C c, SomeBaseClass sbc) { }
}

...

public class X 
{
  public X(SomeBaseClass sbc) { }
}


class Program
{
  static void Main()
  {
    var builder = new ContainerBuilder();
    builder.RegisterInstance(new Child1()).As<SomeBaseClass>();
    var container = builder.Build();

    container.Resolve<A>();

    //Some work here.
  }
}

在某些时候,我想使用Child2而不是Child1实例,并在所有层次结构依赖项中使用它。有没有办法在不构建新容器的情况下做到这一点?有这样的东西是完美的:

public A ResolveWithBinding(IComponentContext cc, SomeBaseClass sbc)
{
   return cc.Resolve<A>().WithRegistered<SomeBaseClass>(sbc);
}

UPD:我找到了某种解决方法:

//Registration code
var factory = new SomeBaseClassAncFactory();
builder.Register(() => factory.GetCurrentInstance()).As<SomeBaseClass>();

//Resolve code
public SomeBaseClass GetCurrentInstance()
{
  if(StaticClass.SomeProperty=="A")
    return new Clild1();
  return new Clild2();
}

我担心这不是真正的线程安全方式。似乎使用静态属性似乎不是最佳实践&#34;。我希望,还有另一个解决方案。

1 个答案:

答案 0 :(得分:1)

实施一个代理类,允许您在Client1Client2之间动态切换。例如:

public class SomeBaseClassProxy : SomeBaseClass 
{
    private Client1 c1;
    private Client2 c2;

    public SomeBaseClassProxy(Client1 c1, Client2 c2) {
        this.c1 = c1;
        this.c2 = c2;
    }

    private GetClient() {
        return StaticClass.SomeProperty == "A" ? c1 : c2;
    }

    // SomeBaseClass methods
    public override void SomeMethod() {
        GetClient().SomeMethod();
    }
}