Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
user351711 Avatar asked Nov 13 '22 08:11

user351711


1 Answers

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.

like image 157
Alex Meyer-Gleaves Avatar answered Dec 21 '22 13:12

Alex Meyer-Gleaves