加载所有引用的程序集.NET,即使未在代码中明确使用 [英] Loading all referenced assemblies .NET even if not used explicitly in code

查看:146
本文介绍了加载所有引用的程序集.NET,即使未在代码中明确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个Windows服务,该服务正在使用Autofac,当我们尝试加载引用的程序集时,由于未在应用程序中的任何位置使用某些包含对象,因此并未列出所有包含的程序集,但需要在其中包含接口实现.以下方法加载程序集:

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;
}

如果我们对程序集中包含的对象进行虚拟引用,则它将加载该程序集,并且类型由autofac构建,如果我们删除该虚拟对象,则不再包含该程序集.

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).

这在ASP.NET上很好用,因为它只将垃圾箱中的所有DLL加载.

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

推荐答案

如果您实际上未在程序集中引用类型,则编译器将删除该引用,因为它被认为是多余的.您需要使用Assembly.Load()将所需的程序集手动加载到AppDomain中.如何确定要加载的装配取决于您自己.您可能选择浏览特定文件夹中的文件,或者使用包含程序集名称的配置文件.

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.

这篇关于加载所有引用的程序集.NET,即使未在代码中明确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆