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

    A markup extension that allows you to resolve an object or service from the configured dependency injection container in XAML. The extension uses the global IocServiceProvider.Default service provider.

    Namespace: DevExpress.Mvvm.UI

    Assembly: DevExpress.Xpf.Core.v26.1.dll

    Declaration

    public class IocExtension :
        MarkupExtension

    Remarks

    Note

    Configure the IocServiceProvider at application startup before you use the IocExtension at runtime.

    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

    See Also