KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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 Autofac for my IoC container, but I don't think that matters too much for this discussion. Injecting a service into the start window seems straightforward, as I can create the container and resolve from it in App.xaml.cs. 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 Resolve() them. 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. Is full IoC possible with WPF? [edit] - Prism has been suggested, but even evaluating Prism seems like a big investment. I'm hoping for something smaller. [edit] here's a code fragment where I'm stopped //setup IoC container (in app.xaml.cs) var builder = new ContainerBuilder(); builder.Register<NewsSource>().As<INewsSource>(); builder.Register<AViewModel>().FactoryScoped(); var container = builder.Build(); // in user control ctor - // this doesn't work, where do I get the container from VM = container.Resolve<AViewModel>(); // 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<AViewModel>();
Tags (comma-separated)
Save Edits
Cancel