Aminion
Aminion

Reputation: 465

Using Unity DI container in WPF application

I'm new in WPF, and consider to try DI. I decide to take OnStartup method as Composition Root.

  protected override void OnStartup(StartupEventArgs e)
    {      
        IUnityContainer container = new UnityContainer();
        container.RegisterType<IMailSender, Model.Concrete.GmailSender>();
        var mainWindow = container.Resolve<MainWindow>();
        mainWindow.Show();
    }

But, after the application is started, appears two windows, normal, with my content, and totally empty (seems like not initialized). What is wrong?

Upvotes: 0

Views: 2541

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

You need to Remove the StartUri in App.XAML. Also it is good practice to set the application main window. Refer below code.

protected override void OnStartup(StartupEventArgs e)
    {
        IUnityContainer container = new UnityContainer();
        container.RegisterType<IMailSender, Model.Concrete.GmailSender>();
        var mainWindow = container.Resolve<MainWindow>();            
        Application.Current.MainWindow = mainWindow;
        Application.Current.MainWindow.Show();
    }

Upvotes: 3

Related Questions