将Unity Container传递给WPF Converter类

时间:2014-06-29 06:42:02

标签: c# wpf converter unity-container

我是WPF的新手。

我想知道如何将IUnityContainer类依赖注入仅在XAML中具有代码的ViewModel。

小更新:
有一个名为LiveVideoTileControl的类 - 我已经将容器添加到它。

我的窗户有一定的转换器:

<UserControl x:Class="Driver.Test.Views.LiveVideoTileControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:ViewModels="clr-namespace:Driver.Test.ViewModel"
         xmlns:Driver="clr-namespace:Driver.Test.DriverRelated"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" >
    <UserControl.Resources>
        <Driver:CameraToMediaElementConverter x:Key="converter"/>
    </UserControl.Resources>
    <ScrollViewer>
    <Grid>
            <ContentControl Content="{Binding  CameraEntity,Converter={StaticResource converter}}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
        </ContentControl>
    </Grid>
    </ScrollViewer>
</UserControl>

如何将容器注入“CameraToMediaElementConverter”类?

class CameraToMediaElementConverter : IValueConverter
{
    public object Convert(object cameraEntity, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((cameraEntity as ICameraEntity) != null)
        {
            return DriverWrapper.GetControlForCamera((ICameraEntity)cameraEntity);
        }
        throw new NotImplementedException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:2)

如果有人会以某种方式到达这里并且仍然会寻找答案,这就是我在我的应用程序中所做的,它运行得很好。转换器类的限制是您不能通过构造函数传递对Unity容器实例的引用以注入您的服务。

在Bootstrapper类或任何其他地方,你在启动时注册你的服务(这里它是Prism的bootstrapper ConfigureContainer的一部分):

   protected override void ConfigureContainer()
    {
        base.ConfigureContainer();
        Container.RegisterType<IShellViewModel, ShellViewModel>();
        Container.RegisterType<MyService>(new ContainerControlledLifetimeManager());
        Container.RegisterInstance<MyService>(new MyService());
        Application.Current.Resources.Add("IoC", this.Container);
    }

注意最后一行:

            Application.Current.Resources.Add("IoC", this.Container);

并在转换器类ctor中:

        UnityContainer unityContainer = (UnityContainer)Application.Current.Resources["IoC"];

现在,您可以从Unity容器中轻松解析任何对象实例:

service = (MyService) unityContainer.Resolve<MyService>();