2013-06-26 6 views
1

객체 B와 C를 A에 주입해야합니다. 객체 C가 B에 의해 사용됩니다 (모든 객체는 Autofac에서 생성됩니다). B가 C를 사용할 필요가없는 경우 (오브젝트 C는 parametrs을 저장하는 데 사용되는) 그리고 나는 이런 식으로 뭔가를 쓸 수있는 하드 코드 된 값을 사용할 수 있습니다Autofac : 주입 된 객체에 주입

 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) { } 
} 

되어 무엇을 찾고있는 것으로 판단 composition root - Autofac은 자동으로 두 번째 생성자를 선택합니다 (C이 등록되어 있고 string이 아닌 것으로 가정).

관련 문제