Loading all referenced assemblies .NET even if not used explicitly in code

断了今生、忘了曾经 提交于 2019-12-10 13:45:47

问题


We have a windows service which is using Autofac, when we try to load the referenced assemblies not all are listed as some contain objects we aren't using anywhere in the application but interface implementations are in there we need to be included. The following method loads the assemblies:

private IEnumerable<Assembly> GetReferencedAssemblies(Assembly assembly)
{
  var assemblyNames = assembly.GetReferencedAssemblies();

  List<Assembly> assemblies = new List<Assembly>();
  assemblies.Add(assembly);
  foreach (var item in assemblyNames)
  {
    var loadedAssembly = System.Reflection.Assembly.Load(item.FullName);
    assemblies.Add(loadedAssembly);
  }

  return assemblies;
}

If we make a dummy reference to an object contained in the assembly then it loads the assembly and the types are built by autofac, if we remove the dummy object the assembly is no longer included.

Is there any way to include all referenced assemblies regardless of whether you are directly using an object in there (bearing in mind we still need it as the interface implementations are in there).

This works fine on ASP.NET as it just loads all DLLs in the bin.


回答1:


If you do not actually reference a type in the assembly the compiler will remove the reference as it is assumed to be redundant. You need to manually load the required assemblies into the AppDomain using Assembly.Load(). How you determine the assemblies to load is up to you. You might choose to look through the files in a particular folder or you perhaps use a configuration file that contains the assemblies names.



来源:https://stackoverflow.com/questions/15788948/loading-all-referenced-assemblies-net-even-if-not-used-explicitly-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!