Note that there are some explanatory texts on larger screens.

plurals
  1. POIs Dependency Injection possible with a WPF application?
    text
    copied!<p>I want to start using dependency injection in my WPF application, largely for better unit testability. My app is mostly constructed along the M-V-VM pattern. I'm looking at <a href="https://code.google.com/p/autofac/" rel="nofollow noreferrer">autofac</a> for my IoC container, but I don't think that matters too much for this discussion.</p> <p>Injecting a service into the start window seems straightforward, as I can create the container and resolve from it in App.xaml.cs. </p> <p>What I'm struggling with is how I can DI ViewModels and Services into User Controls? The user controls are instantiated via XAML markup, so there's no opportunity to <code>Resolve()</code> them.</p> <p>The best I can think of is to place the container in a Singleton, and have the user controls resolve their ViewModels from the global container. This feels like a half-way solution, at best, as it still required my components to have a dependency on a ServiceLocator.</p> <p>Is full IoC possible with WPF?</p> <p>[edit] - Prism has been suggested, but even evaluating Prism seems like a big investment, I'm hoping for something smaller</p> <p>[edit] here's a code fragment where I'm stopped</p> <pre><code> //setup IoC container (in app.xaml.cs) var builder = new ContainerBuilder(); builder.Register&lt;NewsSource&gt;().As&lt;INewsSource&gt;(); builder.Register&lt;AViewModel&gt;().FactoryScoped(); var container = builder.Build(); // in user control ctor - // this doesn't work, where do I get the container from VM = container.Resolve&lt;AViewModel&gt;(); // in app.xaml.cs // this compiles, but I can't use this uc, //as the one I want in created via xaml in the primary window SomeUserControl uc = new SomeUserControl(); uc.VM = container.Resolve&lt;AViewModel&gt;(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload