查找对加载的 dll 的引用
Find references to loaded dlls
我有一个可以通过编写自定义扩展来自定义的应用程序。它们都在 proj\Extensions
文件夹中。在运行时,我的 Core
项目从文件夹中加载每个扩展并执行代码。问题是当其中一个扩展使用额外的库时,因为 Core
项目找不到对这些额外库的引用。
例如在我的 Core
项目中我有:
public void Preview(IFileDescription fileDescription)
{
var extension = Path.GetExtension(fileDescription.FilePath);
var reader = _readerFactory.Get(extension);
Data = reader.GetPreview(fileDescription);
}
在我的一个扩展中我有
public DataTable GetPreview(IFileDescription options)
{
var data = new DataTable();
using (var stream = new StreamReader(options.FilePath))
{
var reader = new CsvReader(stream); // <- This is from external library and because of this Core throws IO exception
}
/*
...
*/
return data;
}
Core
只知道接口,所以当一位读者使用例如 CsvHelper.dll
我得到 FileNotFound
的异常,因为 Core
找不到 CsvHelper.dll
.有没有办法告诉编译器在特定文件夹中查找其他库?我用了Reference Paths
,但是并没有解决问题。它仍然抛出相同的异常。
是的,这是可能的。您可以附加到 AppDomain.AssemblyResolve 事件并从 add-in 目录手动加载所需的 DLL。在执行任何 add-in 代码之前执行以下代码:
var addinFolder = ...;
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
{
var missing = new AssemblyName(e.Name);
var missingPath = Path.Combine(addinFolder, missing.Name + ".dll");
// If we find the DLL in the add-in folder, load and return it.
if (File.Exists(missingPath))
return Assembly.LoadFrom(missingPath);
// nothing found, let .NET search the common folders
return null;
};
我有一个可以通过编写自定义扩展来自定义的应用程序。它们都在 proj\Extensions
文件夹中。在运行时,我的 Core
项目从文件夹中加载每个扩展并执行代码。问题是当其中一个扩展使用额外的库时,因为 Core
项目找不到对这些额外库的引用。
例如在我的 Core
项目中我有:
public void Preview(IFileDescription fileDescription)
{
var extension = Path.GetExtension(fileDescription.FilePath);
var reader = _readerFactory.Get(extension);
Data = reader.GetPreview(fileDescription);
}
在我的一个扩展中我有
public DataTable GetPreview(IFileDescription options)
{
var data = new DataTable();
using (var stream = new StreamReader(options.FilePath))
{
var reader = new CsvReader(stream); // <- This is from external library and because of this Core throws IO exception
}
/*
...
*/
return data;
}
Core
只知道接口,所以当一位读者使用例如 CsvHelper.dll
我得到 FileNotFound
的异常,因为 Core
找不到 CsvHelper.dll
.有没有办法告诉编译器在特定文件夹中查找其他库?我用了Reference Paths
,但是并没有解决问题。它仍然抛出相同的异常。
是的,这是可能的。您可以附加到 AppDomain.AssemblyResolve 事件并从 add-in 目录手动加载所需的 DLL。在执行任何 add-in 代码之前执行以下代码:
var addinFolder = ...;
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
{
var missing = new AssemblyName(e.Name);
var missingPath = Path.Combine(addinFolder, missing.Name + ".dll");
// If we find the DLL in the add-in folder, load and return it.
if (File.Exists(missingPath))
return Assembly.LoadFrom(missingPath);
// nothing found, let .NET search the common folders
return null;
};