2016-05-13 20 views
1

我試圖用Autofac IRegistrationSource解決其他接口,但它不工作。下面是我的代碼:Autofac,MakeGenericMethod.Invoke不能正常工作

public class SettingsSource : IRegistrationSource 
{ 
    static readonly MethodInfo BuildMethod = typeof(SettingsSource).GetMethod(
     "BuildRegistration", 
     BindingFlags.Static | BindingFlags.NonPublic); 

    public IEnumerable<IComponentRegistration> RegistrationsFor(
      Service service, 
      Func<Service, IEnumerable<IComponentRegistration>> registrations) 
    { 
     var ts = service as TypedService; 
     if (ts != null && typeof(ISettings).IsAssignableFrom(ts.ServiceType)) 
     { 
      var buildMethod = BuildMethod.MakeGenericMethod(ts.ServiceType); 
      yield return (IComponentRegistration)buildMethod.Invoke(null, null); 
     } 
    } 

    static IComponentRegistration BuildRegistration<TSettings>() 
     where TSettings : ISettings, new() 
    { 
     return RegistrationBuilder 
      .ForDelegate((c, p) => 
      { 
       return c.Resolve<ISettingService>().LoadSetting<TSettings>(); 
      }) 
      .InstancePerLifetimeScope() 
      .CreateRegistration(); 
    } 

    public bool IsAdapterForIndividualComponents { get { return false; } } 
} 

私有方法c.Resolve()LoadSetting()不能被解僱。

我檢查了波紋管的鏈接,仍然無法弄清楚爲什麼。 Autofac. How to use custom method(property) to resolve some interface?

http://nblumhardt.com/2010/01/declarative-context-adapters-autofac2/

誰能給一個線索?

感謝

+0

您提供的代碼是nopcommerce中設置提供程序註冊的逐字副本。因此,您可以確保它按預期工作,否則根本無法訪問設置。你想做什麼? –

+0

感謝馬可,是的,它來自nopcommerce。我想實現像nopcommerce這樣的系統設置框架。所有由ISettingService運行並在系統啓動時註冊的設置。但我發現fordelegate中的私有函數沒有被解僱。 – LLI

+0

您是否註冊了註冊資源?首先需要調試RegistrationsFor方法以確保它被調用,並在解析繼承ISettings的類時執行yield return子句。有需要設置斷點的地方。 –

回答

0

所提供的代碼,從nopCommerce,完美的作品。我也用它自己,並且效果很好。所以,如果它不能正常工作,問題會出現在你沒有顯示的代碼中,但是我真誠地懷疑它有可能已經在工作。

假設已達到BuildRegistration方法,根據您的意見,它只會返回一個依賴關係規則,而不是服務實例本身。在需要時,稍後懶惰地執行c.Resolve<ISettingService>()調用。你需要在lambda內部設置斷點,看看它發生了什麼。

請注意,BuildRegistration只會爲每個實現ISettings的類調用一次。之後,Autofac將使用提供的規則。

+0

你可以在這裏查看我以前的答案:http://stackoverflow.com/questions/32944127/how-to-load-records-from-setting-table-of-nopcommerce-v3-5/32987318#32987318 –

+0

謝謝Marco,正如我提到的BuildRegistration可以到達的那樣,我試圖在lambda裏面設置斷點,但沒有任何事情發生,根本沒有觸發,這就是爲什麼我知道LoadSetting ()沒有達到。 – LLI

+0

@LLI,如上所述,您需要提供剩餘的代碼(autofac註冊,設置類和用法),因爲您已經提供的代碼是正確的。 –