Problem with Dependency Injection (DI) / IoC for Dynamically Creating Controls and ViewModels

Problem with Dependency Injection (DI) / IoC for Dynamically Creating Controls and ViewModels


I'm working on a WPF application using Autofac for Dependency Injection. The application needs to dynamically create UI controls and their corresponding ViewModels at runtime based on a JSON configuration.

The Problem

  • The ViewModel and Control types are not known at compile-time.
  • ViewModels may have dependencies that need to be resolved via DI.
  • Some custom parameters need to be injected dynamically.
  • The solution should follow IoC and DI principles while avoiding the Service Locator anti-pattern.
### Example JSON Configuration
{
  "Control": "CustomImageControl",
  "ViewModel": "CustomImageControlViewModel",
  "Dependencies": {
    "Filter": "CustomImageFilter"
  },
  "Parameters": {
    "Whatever": "you like"
  }
}


---

The Solution

To solve this, I used a factory pattern combined with Autofac's
IComponentContext
:

  1. **A `ViewModelFactory` that resolves ViewModels dynamically**
    • Uses
      IComponentContext
      to inject dependencies while allowing dynamic parameter setting.
  2. **A `ControlFactory` that resolves UI controls**
    • Assigns the dynamically resolved ViewModel to the control.
  3. **Factories are injected via DI**, avoiding direct use of `IComponentContext` in other parts of the application.
### ViewModel Factory Example
See attachments

This allows for dynamic ViewModel creation with DI-managed dependencies and additional runtime parameters while keeping the system modular, testable, and IoC-compliant.

---

Question

Is this the best way to handle dynamic UI creation with DI, or is there a more efficient approach while still following IoC principles?
Was this page helpful?