2011-10-29 53 views
2

如果支持不同邏輯提供程序的.net應用程序,如何實例化解決方案文件夾中每個類的一個實例?遍歷文件夾中所有類的方法是什麼?加載解決方案文件夾中的所有提供程序類

例如我在我的解決方案中有一個文件夾叫做MailClientProviders 它包含Outlook和The Bat!實現IMailProvider接口的提供者類。

在我的App.xaml中,我調用一個Ninject容器來初始化所有依賴關係。然後,我需要編寫一個我要調用的方法,並獲取返回的每個類的實例。

heartbeatService.Providers = CreateOneInstanceOfAllClassesInProvidresDir(MailClientProviders); 

CreateOneInstanceOfAllClassesInProvidresDir方法會怎麼樣?

+1

MEF似乎更適合這種工作... AFAIK它可以與Ninject等組合/集成。 – Yahia

+1

MEF似乎是我的一個小應用程序的開銷。 –

+0

'MEF'集成在_.NET4_中,我不認爲這會對你的應用程序造成太大的影響。請參閱[這裏](http://mef.codeplex.com/wikipage?title=Guide&referringTitle=Documentation),「MEF」很簡單,完全符合您的需求! – ordag

回答

2

我使用這些函數來檢索文件夾中的所有類實現我的自定義界面:

public static List<T> GetFilePlugins<T>(string filename) 
{ 
    List<T> ret = new List<T>(); 
    if (File.Exists(filename)) 
    { 
     Type typeT = typeof(T); 
     Assembly ass = Assembly.LoadFrom(filename); 
     foreach (Type type in ass.GetTypes()) 
     { 
      if (!type.IsClass || type.IsNotPublic) continue; 
      if (typeT.IsAssignableFrom(type)) 
      { 
       T plugin = (T)Activator.CreateInstance(type); 
       ret.Add(plugin); 
      } 
     } 
    } 
    return ret; 
} 
public static List<T> GetDirectoryPlugins<T>(string dirname) 
{ 
    List<T> ret = new List<T>(); 
    string[] dlls = Directory.GetFiles(dirname, "*.dll"); 
    foreach (string dll in dlls) 
    { 
     List<T> dll_plugins = GetFilePlugins<T>(Path.GetFullPath(dll)); 
     ret.AddRange(dll_plugins); 
    } 
    return ret; 
} 

所以,你可以運行GetDirectoryPlugins<IMailProvider>並使用Activator.CreateInstance與發現每類...

相關問題