Back to Devexpress

Dependency Injection

wpf-403514-mvvm-framework-dependency-injection.md

latest2.6 KB
Original Source

Dependency Injection

  • Feb 24, 2025
  • 3 minutes to read

Bind a View to a View Model

To bind a view to a view model, create a MarkupExtension that resolves the correct ViewModel type:

csharp
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:

csharp
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:

xaml
DataContext="{common:DISource Type=common:MainViewModel}"

Examples

  • Services:

  • POCO:

Use POCO View Models with Dependency Injection

To use a POCO View Model in a Dependency Injection container, utilize the ViewModelSource.GetPOCOType method to register the POCO type generated at runtime:

csharp
container.RegisterType(typeof(IMainViewModel),
                    ViewModelSource.GetPOCOType(typeof(MainViewModel)));

View Example

Use Services with Dependency Injection

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.