[英]Console application wont load assembly by name
I have a console application, which references some of my other projects in the solution. 我有一个控制台应用程序,该应用程序引用了解决方案中的其他一些项目。 On startup, I need to do some reflection work and get the assemblies by name.
启动时,我需要进行一些反射工作并按名称获取程序集。 Apparently, this does not work as expected.
显然,这不符合预期。
I have a project (assembly) called MyApplication.Domain
which I from my .NET MVC project can get by calling GetAssembly("MyApplication.Domain")
using this method: 我有一个名为
MyApplication.Domain
的项目(程序集),我可以从我的.NET MVC项目中通过使用以下方法调用GetAssembly("MyApplication.Domain")
:
public static Assembly GetAssembly(string name)
{
return AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(assembly => assembly.GetName().Name == name);
}
But running this on my console application, just returns null. 但是在我的控制台应用程序上运行它,只会返回null。 The assembly is not even in the
AppDomain.CurrentDomain.GetAssemblies()
list. 该程序集甚至不在
AppDomain.CurrentDomain.GetAssemblies()
列表中。
Then if I try calling this method, using a class in the MyApplication.Domain
assembly, I get the assembly back just like I wish to do using the other method? 然后,如果我尝试使用
MyApplication.Domain
程序集中的类来调用此方法,就可以像使用其他方法一样重新获得该程序集?
public static Assembly[] GetAssembliesOf<T>() where T : class
{
var assemblies = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where typeof (T).IsAssignableFrom(type)
where !type.IsAbstract
select assembly;
return assemblies.ToArray();
}
// Usage: GetAssemblyOf<MyClassInDomainAssembly>();
Things I have checked: 我检查过的事情:
Is there some funky stuff I need to know about loading assemblies in console application? 关于在控制台应用程序中加载程序集,我需要了解一些时髦的知识吗?
As a side note the console application is actually a Self-Host Web API 2. 附带一提,控制台应用程序实际上是Self-Host Web API 2。
Your observations are correct and expected. 您的观察是正确和预期的。 .Net is lazy and the collection in question will be filled as your assemblies get loaded and they are loaded only when they are used.
.Net是惰性的,有问题的集合将在您的程序集被加载时填充,并且仅在使用它们时才加载它们。 The fact that you can observe this in console application and not in mvc is just because your console application did less before you executed that line.
您可以在控制台应用程序中而不是在mvc中观察到这一事实,这仅仅是因为控制台应用程序在执行该行之前所做的工作较少。
More over when you have reference to an assembly finding it by name is just pointless as you can do typeof(AnyTypeFromThatAssembly).Assembly
. 当您引用程序集时,按名称查找它是没有意义的,因为您可以执行
typeof(AnyTypeFromThatAssembly).Assembly
。 And if you really want to load an assembly by name you can executed Assembly.Load
but this requires fully qualified assembly name which you can get again by typeof(AnyTypeFromThatAssembly).Assembly.FullName.ToString()
. 而且,如果您真的想按名称加载程序集,则可以执行
Assembly.Load
但这需要完全限定的程序集名称,您可以通过typeof(AnyTypeFromThatAssembly).Assembly.FullName.ToString()
再次获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.