亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創建實例并解決依賴關系

創建實例并解決依賴關系

C#
藍山帝景 2022-01-15 19:25:26
我有在主項目中引用的 c# 庫。圖書館獲取主項目程序集;System.Reflection使用;檢索所有類型應該使用創建類型Activator.CreateInstance(我不確定這是最好的方法)。該庫對主項目一無所知,只有一個可以通過反射獲得的元數據。如何解決依賴關系?private readonly Assembly _assembly;public Injector(){    _assembly = Assembly.GetEntryAssembly();}public List<string> GetTypes(){    return _assembly        .GetTypes()        .Select(x => x.FullName)        .ToList();}public object GetType(string typeName){    Type type = _assembly        .GetTypes()        .First(x => x.FullName == typeName);    object instance = Activator.CreateInstance(type);    return instance;}可能的問題:不同的 IoC 容器(第三方庫,自己編寫的)。在不強制用戶提供大量設置的情況下,處理此問題并使庫更加自動化的最佳方法是什么?如果不可能,您能否提供任何其他解決方案?謝謝。編輯:如何提供對實例的依賴關系Activator.CreateInstance或直接從主(源)項目創建實例?應該允許創建包含在主項目中的任何實例。是的,主項目也對圖書館一無所知。因此,希望在主項目中進行最少的代碼更改。編輯 2:該庫不會在源項目中使用,它將有自己的 UI 界面。例如,Swagger API
查看完整描述

1 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

只要解析的庫在同一文件夾下(或在 GAC 中),依賴關系就會自動解析 如果庫在特定文件夾下,自動解析可能會失敗,但您可以使用AppDomain.AssemblyResolve事件處理它。


此外,您似乎正在嘗試實現一種插件/插件主機,也許您可以嘗試使用托管可擴展性框架而不是通過反射手動實現解決方案。


編輯:遵循事件使用的代碼片段,但需要根據您的環境進行調整


static Injector()

{

     // Usage of static constructor because we need a unique static handler

     // But feel free to move this part to a more global location

     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

}


private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)

{

  string foundAssemblyPath = string.Empty;


  // args.Name contains name of the missing assembly

  // some project-specific and environment-specific code should be added here to manually resolve the dependant library

  // In this example I will consider that the libraries are located under /plugins folder

  foundAssemblyPath = $@"{Path.GetDirectoryName(Application.StartupPath)}\plugins\{args.Name}.dll";


  return Assembly.LoadFile(foundAssemblyPath);

}


查看完整回答
反對 回復 2022-01-15
  • 1 回答
  • 0 關注
  • 169 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號