Skip to main content
All docs
V26.1
  • IocServiceProvider Class

    A global wrapper for an application service provider that enables dependency injection in the DevExpress MVVM framework.

    Namespace: DevExpress.Mvvm

    Assembly: DevExpress.Mvvm.v26.1.dll

    Declaration

    public sealed class IocServiceProvider :
        IServiceProvider

    The following members return IocServiceProvider objects:

    Remarks

    Configure the application dependency injection container at startup and assign it to the IocServiceProvider.Default service. The IocExtension can resolve MainViewModel from XAML during initialization:

    using DevExpress.Mvvm;
    using Microsoft.Extensions.DependencyInjection;
    using MvvmApp.ViewModels;
    
    namespace MvvmApp {
        public partial class App : Application {
            // ...
            protected override void OnStartup(StartupEventArgs e) {
                IServiceProvider services = new ServiceCollection()
                    .AddTransient<MainViewModel>()
                    .BuildServiceProvider();
                // Configure the global provider before WPF starts loading StartupUri/XAML
                // The {dxmvvm:Ioc ...} config can resolve types during initialization in XAML
                IocServiceProvider.Default.ConfigureServices(services);
                base.OnStartup(e);
    
                var mainWindow = new MainWindow();
                MainWindow = mainWindow;
                mainWindow.Show();
            }
        }
    }
    

    Declare a MainViewModel class with a read-only Message property that contains text for UI binding:

    namespace MvvmApp.ViewModels {
        public sealed class MainViewModel {
            public string Message { get; } = "DI works through the IocExtension";
        }
    }
    

    Use the IocExtension to resolve a MainViewModel from the configured Dependency Injection container. The window sets the resolved MainViewModel instance as DataContext, so the TextBlock can bind to the Message property:

    <dx:ThemedWindow
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
        xmlns:vm="clr-namespace:MvvmApp.ViewModels"
    
        DataContext="{dxmvvm:Ioc Type={x:Type vm:MainViewModel}}">
    
        <Grid>
            <TextBlock Text="{Binding Message}"/>
        </Grid>
    </dx:ThemedWindow>
    

    Inheritance

    Object
    IocServiceProvider
    See Also