是否有方法强制将所有引用的程序集加载到应用程序域中?

我的项目是这样设置的:

  • 「定义」计划
  • 项目「推行」
  • “消费者”计划

项目“消费者”同时引用“定义”和“实现”,但不静态引用“实现”中的任何类型。

当应用程序启动时,Project“ Consumer”在“ Definition”中调用一个静态方法,该方法需要在“ Laboratory”中查找类型

有没有一种方法,我可以强制任何引用的程序集加载到应用程序域,而不知道路径或名称,最好不必使用完全成熟的 IOC 框架?

82034 次浏览

You can use Assembly.GetReferencedAssemblies to get an AssemblyName[], and then call Assembly.Load(AssemblyName) on each of them. You'll need to recurse, of course - but preferably keeping track of assemblies you've already loaded :)

This seemed to do the trick:

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();
            

var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();


toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));

As Jon noted, the ideal solution would need to recurse into the dependencies for each of the loaded assemblies, but in my specific scenario I don't have to worry about it.


Update: The Managed Extensibility Framework (System.ComponentModel) included in .NET 4 has much better facilities for accomplishing things like this.

If you use Fody.Costura, or any other assembly merging solution, the accepted answer will not work.

The following loads the Referenced Assemblies of any currently loaded Assembly. Recursion is left to you.

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();


loadedAssemblies
.SelectMany(x => x.GetReferencedAssemblies())
.Distinct()
.Where(y => loadedAssemblies.Any((a) => a.FullName == y.FullName) == false)
.ToList()
.ForEach(x => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(x)));

just wanted to share a recursive example. I'm calling the LoadReferencedAssembly method in my startup routine like this:

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
this.LoadReferencedAssembly(assembly);
}

This is the recursive method:

private void LoadReferencedAssembly(Assembly assembly)
{
foreach (AssemblyName name in assembly.GetReferencedAssemblies())
{
if (!AppDomain.CurrentDomain.GetAssemblies().Any(a => a.FullName == name.FullName))
{
this.LoadReferencedAssembly(Assembly.Load(name));
}
}
}

Seeing as I had to load an assembly + dependencies from a specific path today I wrote this class to do it.

public static class AssemblyLoader
{
private static readonly ConcurrentDictionary<string, bool> AssemblyDirectories = new ConcurrentDictionary<string, bool>();


static AssemblyLoader()
{
AssemblyDirectories[GetExecutingAssemblyDirectory()] = true;
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;


}


public static Assembly LoadWithDependencies(string assemblyPath)
{
AssemblyDirectories[Path.GetDirectoryName(assemblyPath)] = true;
return Assembly.LoadFile(assemblyPath);
}


private static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
string dependentAssemblyName = args.Name.Split(',')[0] + ".dll";
List<string> directoriesToScan = AssemblyDirectories.Keys.ToList();


foreach (string directoryToScan in directoriesToScan)
{
string dependentAssemblyPath = Path.Combine(directoryToScan, dependentAssemblyName);
if (File.Exists(dependentAssemblyPath))
return LoadWithDependencies(dependentAssemblyPath);
}
return null;
}


private static string GetExecutingAssemblyDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}

Yet another version (based on Daniel Schaffer answer) is the case when you might not need to load all Assemblies, but a predefined number of them:

var assembliesToLoad = { "MY_SLN.PROJECT_1", "MY_SLN.PROJECT_2" };


// First trying to get all in above list, however this might not
// load all of them, because CLR will exclude the ones
// which are not used in the code
List<Assembly> dataAssembliesNames =
AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly => AssembliesToLoad.Any(a => assembly.GetName().Name == a))
.ToList();


var loadedPaths = dataAssembliesNames.Select(a => a.Location).ToArray();


var compareConfig = StringComparison.InvariantCultureIgnoreCase;
var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll")
.Where(f =>
{
// filtering the ones which are in above list
var lastIndexOf = f.LastIndexOf("\\", compareConfig);
var dllIndex = f.LastIndexOf(".dll", compareConfig);


if (-1 == lastIndexOf || -1 == dllIndex)
{
return false;
}


return AssembliesToLoad.Any(aName => aName ==
f.Substring(lastIndexOf + 1, dllIndex - lastIndexOf - 1));
});


var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();


toLoad.ForEach(path => dataAssembliesNames.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));


if (dataAssembliesNames.Count() != AssembliesToLoad.Length)
{
throw new Exception("Not all assemblies were loaded into the  project!");
}

If you have assemblies where no code is referenced at compile time, those assemblies will not be included as a reference to your other assembly, even if you have added the project or nuget package as a reference. This is regardless of Debug or Release build settings, code optimization, etc. In these cases, you must explicitly call Assembly.LoadFrom(dllFileName) to get the assembly loaded.

For getting referenced assembly by name you can use following method:

public static Assembly GetAssemblyByName(string name)
{
var asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == name);
if (asm == null)
asm = AppDomain.CurrentDomain.Load(name);
return asm;
}

In my winforms application I give JavaScript (in a WebView2 control) the possibility to call various .NET things, for example methods of Microsoft.VisualBasic.Interaction in the assembly Microsoft.VisualBasic.dll (such as InputBox() etc).

But my application as such does not use that assembly, so the assembly is never loaded.

So to force the assembly to load, I ended up simply adding this in my Form1_Load:

if (DateTime.Now < new DateTime(1000, 1, 1, 0, 0, 0)) { // never happens
Microsoft.VisualBasic.Interaction.Beep();
// you can add more things here
}

The compiler thinks that the assembly might be needed, but in reality this never happens of course.

Not a very sophisticated solution, but quick and dirty.

I created my own based on @Jon Skeet answer with name prefix filtering to avoid loading unnecessary assemblies:

public static IEnumerable<Assembly> GetProjectAssemblies(string prefixName)
{
var assemblies = new HashSet<Assembly>
{
Assembly.GetEntryAssembly()
};


for (int i = 0; i < assemblies.Count; i++)
{
var assembly = assemblies.ElementAt(i);


var referencedProjectAssemblies = assembly.GetReferencedAssemblies()
.Where(assemblyName => assemblyName.FullName.StartsWith(prefixName))
.Select(assemblyName => Assembly.Load(assemblyName));


assemblies.UnionWith(referencedProjectAssemblies);
}


return assemblies;
}