Samuel Marvin Aguilos
Samuel Marvin Aguilos

Reputation: 165

Run a WPF Project from a DLL starting from its App.xaml.cs

I have a WPF project that should be able to run independently and can also run as a reference DLL.

I am trying to run the WPF project from another WPF project

Project1 needs to load Project2

Project1 needs to run Project2 as a whole from its App.xaml.cs since this is where DataContexts gets binded. Here is the App.xaml.cs of Project2:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
    Dictionary<Type, Type> viewRegistry = new Dictionary<Type, Type>();

    viewRegistry.Add(typeof(ImageUploaderViewModel), typeof(ImageUploaderView));
    viewRegistry.Add(typeof(CodBoxViewModel), typeof(CodBoxView));

    Type viewType = viewRegistry[typeof(ImageUploaderViewModel)];

    MessageBox.Show("Hello World");

    Window view = (Window)Activator.CreateInstance(viewType);
    view.DataContext = new ImageUploaderViewModel(viewRegistry);
    view.Show();

    }
}

Here is where I try to call the Project 2

private void LoadProject2()
{
    string assemblyName = string.Format("{0}\\Project2.dll", new 
    FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName);
    Application app = LoadAssembly(assemblyName, "App");
    app.Run();
}

private Application LoadAssembly(String assemblyName, String typeName)
{
   try
   {
       Assembly assemblyInstance = Assembly.LoadFrom(assemblyName);
       
       Application app;
       
       foreach (Type t in assemblyInstance.GetTypes().Where(t => String.Equals(t.Name, typeName, StringComparison.OrdinalIgnoreCase)))
       {
           app = assemblyInstance.CreateInstance(t.FullName) as Application;
           return app;
       }
   }
   catch (Exception ex)
   {
       System.Diagnostics.Trace.WriteLine(string.Format("Failed to load window from{0}{1}", assemblyName, ex.Message));
       throw new Exception(string.Format("Failed to load external window{0}", assemblyName), ex);
   }
}

With this I am able to get the Application but I get an error "Cannot create more than one System.Windows.Application instance in the same AppDomain.". I am not sure how to make this possible without having 2 Application instance. Thank you

Upvotes: 0

Views: 542

Answers (1)

mm8
mm8

Reputation: 169320

If you want to start another app, you should compile the other app and start it in a new process using the Process.Start API.

You cannot run two WPF applications in the same process, and it doesn't make any sense to do so either.

If the DataContexts gets binded in App.xaml.cs, you should probably refactor your code into a separate class library that you can include from any application. Move the code from OnStartup into a decopupled method of class in a class library and simply call this method from the OnStartup method of the single running application.

Upvotes: 1

Related Questions