DependencyInjectionContainer
TheDependencyInjectionContainer class (source:UiMetadataFramework.Core/Binding/DependencyInjectionContainer.cs:8) is a simple wrapper around IServiceProvider:
Default Container Behavior
By default, UIMF usesActivator.CreateInstance to instantiate types. This works for types with parameterless constructors:
Integrating with Your DI Container
You can integrate UIMF with any dependency injection framework by providing a customIServiceProvider.
ASP.NET Core Example
Autofac Example
Simple Function-Based Container
For simple scenarios, you can use a function-based approach:Where DI is Used
UIML uses dependency injection in several places:1. Metadata Factories
When a component has a custom metadata factory, UIMF instantiates it using the DI container:2. Inline Data Sources
Inline sources are instantiated via DI, allowing them to access your application’s services:3. Custom Field Metadata Factories
When configuring a custom field metadata factory:Controlling Instance Lifetime
The DI container is called every time an instance is needed. To control lifetime:Singleton Pattern
Using Your DI Container’s Lifetime Management
Testing with DI
Dependency injection makes testing easier by allowing you to inject mocks:Best Practices
- Use constructor injection: Inject dependencies through constructors for clarity and testability
- Register factories: Register your metadata factories in the DI container with appropriate lifetimes
- Avoid service locator pattern: Don’t call
container.GetService()directly in business logic; use it only in framework extension points - Keep factories stateless: Metadata factories should be stateless to work correctly with any lifetime
- Document dependencies: Clearly document what services your components need
- Test with mocks: Use DI to inject mocks in unit tests
Common Patterns
Factory with Configuration
Factory with Multiple Dependencies
Lazy Service Resolution
Next Steps
- Learn how to create custom components
- Understand metadata factories
- See client integration patterns