我有两个C#项目。第一个项目的输出是一个DLL(Visual Studio中的输出类型设置为Class Library),它使我可以从其他语言控制我的应用程序。它基本上在不显示任何UI窗口的情况下启动我的应用程序的实例。我可以在其他编程语言(例如Python,Matlab)中使用此DLL,而不会出现任何问题。
但是现在我想在另一个C#项目中使用该DLL。为此,我在项目中添加了DLL作为参考。要启动我的应用程序的实例,我创建了DLL中定义的类型的对象:
namespace MyDLL
{
class Program
{
static void Main(string[] args)
{
MyApp app = new MyApp();
}
}
}
这导致异常:
System.InvalidOperationException: 'The 'ResourceAssembly' property of the 'Application' type cannot be changed after it has been set.'
此异常的原因是MyApp
设置ResourceAssembly
以便加载应用程序的资源(如UI图像之类的事实:
System.Windows.Application.ResourceAssembly = typeof(AppBase.MainWindow).Assembly;
由于Application.ResourceAssembly
只能设置一次,因此我尝试了一种解决方法,如the second solution of this StackOverflow post中所述。这样可以防止引发ResourceAssembly异常。
DLL对象尝试启动,但随后引发以下异常:
System.InvalidOperationException: 'The Application object is being shut down.'
此异常的InnerException值为null
,但其源值为PresentationFramework
。这是异常的StackTrace:
at System.Windows.Application.GetResourcePackage(Uri packageUri)
at System.Windows.Application.GetResourceOrContentPart(Uri uri)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at App.MainWindow..ctor(Boolean showWindow)
at MyDLL.MyApp.startApp()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()