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"
}
}
{
"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?
1 Reply
Anton
Anton2mo ago
You either have to use a library like you did, reimplement the features of the library you need, or manually make factories for each class what you did makes sense

Did you find this page helpful?