wpf-403514-mvvm-framework-dependency-injection.md
To bind a view to a view model, create a MarkupExtension that resolves the correct ViewModel type:
public class DISource : MarkupExtension {
public static Func<Type, object, string, object> Resolver { get; set; }
public Type Type { get; set; }
public object Key { get; set; }
public string Name { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider) => Resolver?.Invoke(Type, Key, Name);
}
Register the resolver at the application startup:
protected override void OnStartup(StartupEventArgs e) {
base.OnStartup(e);
DISource.Resolver = Resolve;
}
object Resolve(Type type, object key, string name) {
if(type == null)
return null;
if(key != null)
return Container.ResolveKeyed(key, type);
if(name != null)
return Container.ResolveNamed(name, type);
return Container.Resolve(type);
}
Specify the DataContext in XAML in the following manner:
DataContext="{common:DISource Type=common:MainViewModel}"
Services:
POCO:
To use a POCO View Model in a Dependency Injection container, utilize the ViewModelSource.GetPOCOType method to register the POCO type generated at runtime:
container.RegisterType(typeof(IMainViewModel),
ViewModelSource.GetPOCOType(typeof(MainViewModel)));
The recommended technique to use DevExpress services with Dependency Injection varies depending on whether the service has an associated visual element.
If the service is attached to a specific visual element, add the following custom AttachServiceBehavior to register it:
If the service does not need to be attached to a specific visual element (such as Message Box Services), you can use the following technique instead:
Tip
If you configure the service to work with a specific View, Dependency Injection is not recommended. Use the technique described in the following section instead: Implement Services in Your Application.