2010-08-05 2 views
7

응용 프로그램 도메인, 을 사용하여 콘솔 응용 프로그램에서 WPF 응용 프로그램을 시작하려고하지만 예상치 못한 오류가 발생합니다.새 AppDomain에서 WPF 응용 프로그램을 어떻게 실행합니까? ExecuteAssembly가 실패합니다.

WPF 응용 프로그램을 독립 실행 형으로 실행하면 작동합니다.

var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; 
var path = string.Format("{0}AddressbookDesktop.exe", baseDirectory); 
var processInfo = new ProcessStartInfo(path, ""); 
Process.Start(processInfo);  

을하지만이 코드는 아래의 오류와 함께 실패 :

이 코드도 작동합니다.

var addressbookDomain = AppDomain.CreateDomain("addressbookDomain"); 
addressbookDomain.ExecuteAssembly("AddressbookDesktop.exe"); 

스택 추적 :이 오류는 비어 생성자에 나타납니다

System.Windows.Markup.XamlParseException: Cannot create instance of 
'AddressbookMainWindow' defined in assembly 'AddressbookDesktop, Version=1.0.0.0, 
Culture=neutral, PublicKeyToken=null'. Exception has been thrown 
by the target of an invocation. Error in markup file 'AddressbookMainWindow.xaml' Line  1 Position 9. 
---> System.Reflection.TargetInvocationException: Exception has been thrown by the 
target of an invocation. ---> System.InvalidOperationException: The calling thread must 
be STA, because many UI components require this. 

at System.Windows.Input.InputManager..ctor() 
at System.Windows.Input.InputManager.GetCurrentInputManagerImpl() 
at System.Windows.Input.InputManager.get_Current() 
at System.Windows.Input.KeyboardNavigation..ctor() 
at System.Windows.FrameworkElement.FrameworkServices..ctor() 
at System.Windows.FrameworkElement.EnsureFrameworkServices() 
at System.Windows.FrameworkElement..ctor() 
at System.Windows.Controls.Control..ctor() 
at System.Windows.Controls.ContentControl..ctor() 
at System.Windows.Window..ctor() 
at XX.YY.AddressbookDesktop.AddressbookMainWindow..ctor() in  C:\.....\AddressBookDesktop\AddressbookMainWindow.xaml.cs:line 15 
--- End of inner exception stack trace --- 

내가 뭔가를 잘못하고 있어요 생각하지만, 그것이 무엇인지 이해할 수 없습니다. 도움 주셔서 감사합니다.

답변

8

문제는 WPF가 STA 스레드 (위에서 언급 한 내부 예외 중 하나)에서 실행되어야한다는 것입니다. 나는 STAThreadAttribute을 내 Main() 방법에 추가하여 작동하게했습니다 :

using System; 

class Program 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 
     Console.WriteLine("Starting WpfApplication1.exe..."); 

     var domain = AppDomain.CreateDomain("WpfApplication1Domain"); 
     try 
     { 
      domain.ExecuteAssembly("WpfApplication1.exe"); 
     } 
     catch(Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 
     finally 
     { 
      AppDomain.Unload(domain); 
     } 

     Console.WriteLine("WpfApplication1.exe exited, exiting now."); 
    } 
}