简体   繁体   English

依赖链中的Autofac更改实例

[英]Autofac change instance in dependency chain

I'm having an hierarchy that looks smth like: 我有一个看起来像这样的层次结构:

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.
  }
}

At some point of time I would like to use Child2 instead of Child1 instance and use it in all hierarchy dependencies. 在一定的时间点,我想用Child2代替Child1实例,并在所有层次的依赖使用它。 Is there a way to do this without building new Container? 有没有一种方法,而无需构建新的Container? It would be perfect to have something like: 拥有以下内容将是完美的:

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

UPD: I've found some sort of workaround: 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();
}

And I'm afraid that it is not really thread-safe way. 而且我担心这不是真正的线程安全方式。 And it seems like using static properties is not a "best practice". 似乎使用静态属性不是“最佳实践”。 I hope, there's another solution. 我希望还有另一种解决方案。

Implement a proxy class that allows you to switch dynamically between Client1 and Client2 . 实现允许您在Client1Client2之间动态切换的代理类。 For instance: 例如:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM