2011-01-23 65 views
6

例如,我在類型爲System.Type的構造函數中註冊了具有一個參數的類C1。我有另一個類(C2)注入類型爲C1的參數。我想在C1構造函數中自動接收typeof(C2)。在某種程度上可能嗎?是否有可能在AutoFac中獲取容器類型

示例代碼:

public class C1 
{ 
    public C1(Type type) {} 

    // ... 
} 

public class C2 
{ 
    public C2(C1 c1) {} 

    // ... 
} 

// Registration 
containerBuilder.Register(???); 
containerBuilder.Register<C2>(); 

回答

7

這應做到:

builder.RegisterType<C1>(); 
builder.RegisterType<C2>(); 
builder.RegisterModule(new ExposeRequestorTypeModule()); 

其中:

class ExposeRequestorTypeModule : Autofac.Module 
{ 
    Parameter _exposeRequestorTypeParameter = new ResolvedParameter(
     (pi, c) => c.IsRegistered(pi.ParameterType), 
     (pi, c) => c.Resolve(
      pi.ParameterType, 
      TypedParameter.From(pi.Member.DeclaringType))); 

    protected override void AttachToComponentRegistration(
      IComponentRegistry registry, 
      IComponentRegistration registration) 
    { 
     registration.Preparing += (s, e) => { 
      e.Parameters = new[] { _exposeRequestorTypeParameter } 
       .Concat(e.Parameters); 
     }; 
    } 
} 

,需要一個System.Type參數將獲得通過的請求的類型的任何組件(如果有的話)。可能的改進可能是使用NamedParameter而不是比TypedParameter限制Type參數將只匹配具有某個名稱的參數。

請讓我知道這是否有效,其他人詢問了相同的一般任務,這將是很好的與他們分享。

+0

不,不幸的是,它不起作用。 LimitType是組件本身的類型(本例中爲C1) – oryol 2011-01-24 19:04:46

相關問題