2011-10-20 33 views
3

我正在開發一個應用程序。我希望統一解決我的類型,而不必在主項目中引用程序集。我通過使用配置類型註冊來自動加載程序集,但似乎不起作用,除非我添加對包含依賴關係的程序集的引用。Unity容器可以動態裝載組件嗎?

有沒有從當前目錄中的程序集加載類型?

謝謝!

+0

您使用的是xml配置嗎? –

回答

0

這可能是有點晚,以幫助,但團結可以動態加載組件如果使用XML配置方法,註冊的每個組件,然後註冊類型因此。現在,我一直在使用這個過程對一段時間內非常重的DI框架進行小擴展。

如果您遇到團結不能解決其註冊在主應用程序,但在另一個定義的類型的問題,未引用的裝配和參考上述組件可以解決問題,那最有可能意味着它只是WASN」 t複製到應用程序的輸出目錄。默認情況下,僅自動複製直接引用的程序集。如果它們是手動複製或生成後事件複製的,或者如果您重定向構建路徑以使未引用的程序集生成到應用程序的輸出目錄,則它應該應該工作。

1

我知道這是前一段時間提出的,但對於任何尋找答案的人來說,您必須確保Unity能夠在運行時找到程序集。因此,您需要將它們放入GAC或將您的程序集dll放在與可執行文件相同的目錄中。如果你正在使用的依賴不同的目錄中,有一個Web應用程序,那麼你必須設置探測元素在你的web.config:

<runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <probing privatePath="Dependencies" /> 
    </assemblyBinding> 
</runtime> 

而對於有人在那裏找了一段代碼如何解決這個問題,下面的代碼將查找您定義的目錄上的所有程序集,並使用Unity註冊它們:

string DependenciesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dependencies"); 
string[] Dependencies = Directory.GetFiles(DependenciesPath, DLL_PATTERN); 

Dictionary<Type, Type> pluginMappings = new Dictionary<Type, Type>(); 

//Load Dependency Assemblies 
foreach (string fileName in Dependencies) 
{ 
    string assemblyName = Path.GetFileNameWithoutExtension(fileName); 
    if (assemblyName != null) 
    { 
     Assembly pluginAssembly = Assembly.Load(assemblyName); 

     foreach (Type pluginType in pluginAssembly.GetTypes()) 
     { 
      if (pluginType.IsPublic) //Only look at public types 
      { 
       if (!pluginType.IsAbstract) //Only look at non-abstract types 
       { 
        //Gets a type object of the interface we need the plugins to match 
        Type[] typeInterfaces = pluginType.GetInterfaces(); 
        foreach (Type typeInterface in typeInterfaces) 
        { 
         if (pluginMappings.ContainsKey(typeInterface)) 
         { 
          throw new DuplicateTypeMappingException(typeInterface.Name, typeInterface, pluginMappings[typeInterface], pluginType); 
         } 
         pluginMappings.Add(typeInterface, pluginType); 
        } 
       } 
      } 
     } 
    } 
} 

//Web API resolve dependencies with Unity 
IUnityContainer container = new UnityContainer(); 
foreach (var mapping in pluginMappings) 
{ 
    container.RegisterType(mapping.Key, mapping.Value); 
} 
相關問題