2013-06-26 118 views
1

我需要注入对象B和C到A,其中对象C被B使用(所有对象都在Autofac中创建)如果不需要B使用C (对象C用于存储parametrs),我可以使用硬编码值我可以写这样的事:Autofac:注入注入对象(解决dificult依赖关系)

 builder.RegisterType<B>().As<IB>().WithParameter("key","value"); 

但我应该怎么做,如果parametrs通过autofac产生的?

 builder.RegisterType<B>().As<IB>().WithParameter("key",C.value); 

回答

0

我相信这是你在找什么

class B 
{ 
    public B(string key, C anotherDependency) 
    { 
     this.Key = key; 
    } 

    public string Key { get; private set; } 
} 

class C 
{ 
    public string Value { get { return "C.Value"; } } 
} 

[TestMethod] 
public void test() 
{ 
    var cb = new ContainerBuilder(); 

    cb.RegisterType<B>().WithParameter(
     (prop, context) => prop.Name == "key", 
     (prop, context) => context.Resolve<C>().Value); 

    cb.RegisterType<C>(); 

    var b = cb.Build().Resolve<B>(); 
    Assert.AreEqual("C.Value", b.Key); 
} 

你可能要考虑的另一种方式是这个

class B 
{ 
    public B(string key) { ... } 

    public B(C c) : this(c.Value) { } 
} 

,这意味着你不需要任何的特殊组合根 - Autofac会自动选择第二个构造函数(假设C已注册,而string不是)。