概述
目标
我有两个C#项目。第一个项目的输出是一个DLL(在Visual Studio中的输出类型设置为类库),可以让我从其他语言控制我的应用程序。它基本上启动了一个不显示任何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
只能设置一次,所以我尝试了一种方法来绕过它,如这篇StackOverflow帖子的第二个解决方案所述。这可以防止ResourceAssembly异常被抛出。
然后DLL对象尝试启动,但随后抛出以下异常:
System.InvalidOperationException: 'The Application object is being shut down.'
此异常的InnerException值为
null
,但其源值为PresentationFramework
。以下是该异常的堆栈跟踪: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()