2

I want to use Unity dependency injection in WPF application. My Window throw System.Windows.Markup.XamlParseException:

"For type MainWindow found no default constructor".

This is my code:

App.xaml.cs:

IUnityContainer container = new UnityContainer();
container.RegisterType<MainWindow>();
container.RegisterType<IService, MyService>();
container.RegisterType<IRepository, MyRepository>();
container.Resolve<MainWindow>().Show();

MainWindow.xaml.cs:

public MainWindow(IService service)
{
     InitializeComponent();
     service.Test();
}
ViVi
  • 4,339
  • 8
  • 29
  • 52
bluray
  • 1,875
  • 5
  • 36
  • 68

1 Answers1

3

You always need to have a default constructor for your view in order for your WPF application to work properly.

public MainWindow()
{
     InitializeComponent();
}

and then define the parameterized constructor like this :

public MainWindow(IService service) : this()
{
     service.Test();
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
ViVi
  • 4,339
  • 8
  • 29
  • 52
  • 2
    You need the parameterized constructor to call the default constructor with a `:this()` at the end of the method signature. otherwise `InitializeComponent();` won't get called – Scott Chamberlain Aug 01 '16 at 13:53
  • 2
    Default ctor needed only if views instantiated via XAML, right? If we instantiate views from code, view is not nave to have default ctor. – tym32167 Aug 01 '16 at 14:07
  • Imho, this does not address the OPs problem of Unity not calling the parameterized constructor with constructor injection. – Dirk Vollmar Aug 01 '16 at 14:50
  • I agree with @tym32167. But this is a **MainWindow**. How does it work without a default constructor, even if we write everything in code behind? – ViVi Aug 01 '16 at 16:57
  • @Scott Chamberlain : Sorry I missed it. Thanks for the edit. – ViVi Aug 01 '16 at 16:59
  • @IDisposable It will work ok, if you are using some DI container to create an instance of MainWindow (as example https://github.com/tym32167/arma3beclient/blob/c53fc1e97794d900e508ae425298e05b90c765c2/src/Arma3BE.Client/Bootstrapper.cs#L26 ) – tym32167 Aug 01 '16 at 18:18