2010-08-05 7 views
7

J'essaie de lancer une application WPF à partir d'une application console, en utilisant les domaines d'application, mais lorsque je le fais, je reçois des erreurs inattendues.Comment puis-je exécuter une application WPF dans un nouvel AppDomain? ExecuteAssembly échoue

Exécution de l'application WPF autonome, fonctionne.

Ce code fonctionne aussi:

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

Mais ce code échoue avec l'erreur ci-dessous. L'erreur semble être dans le constructeur, qui est vide:

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

Trace de la pile:

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

Je suppose que je fais quelque chose de mal, mais ne peut pas comprendre ce qu'il est. Merci pour toute aide.

Répondre

8

Le problème est que WPF doit être exécuté à partir d'un thread STA (l'une des exceptions internes ci-dessus l'indique). Je l'ai eu à travailler en ajoutant le STAThreadAttribute à ma méthode 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."); 
    } 
} 
Questions connexes