Unity:依赖注入

时间:2010-06-08 14:14:47

标签: unity-container

公共部分类HTCmds:ResourceDictionary         {             private ICanvasService mCanvasService;

        [Dependency]
        public ICanvasService CanvasService
        {
            get { return mCanvasService; }
            set { mCanvasService = value; }
        }

        public HTCmds()
        {
            CopyCommand = new DelegateCommand<object>(this.Copy, this.CanCopy);
            ExitCommand = new DelegateCommand<object>(this.Exit);
        }

        public DelegateCommand<object> CopyCommand { get; private set; }
        public DelegateCommand<object> ExitCommand { get; private set; }
}

资源字典Xaml:

<ResourceDictionary x:Class="HTCmds" 
                    x:ClassModifier="public"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:commands="clr-namespace:Commands;assembly=UIInfrastructure"
                    xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
                    xmlns:local="clr-namespace:Commands.Commands">
    <local:HTCmds x:Key="thisobj"/>
    <commands:CommandReference x:Key="CopyCommandReference" Command="{Binding  Source={StaticResource thisobj}, Path=CopyCommand}"/>
    <commands:CommandReference x:Key="ExitCommandReference" Command="{Binding  Source={StaticResource thisobj}, Path=ExitCommand}"/>
</ResourceDictionary>

我已经注册了ICanvasService但是没有注入这个类。资源字典合并在windows类的xaml文件中:

<ResourceDictionary>
     <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../Commands/HTCmds.xaml" />
     </ResourceDictionary.MergedDictionaries>
 </ResourceDictionary>

是否有针对ResourceDictionary类的特定内容?

谢谢&amp;问候, 维沙尔。

1 个答案:

答案 0 :(得分:1)

您的HTCmds对象由WPF通过以下XAML行创建:

<local:HTCmds x:Key="thisobj"/>

WPF不了解Unity,所以它不知道如何使用Unity解决依赖关系。您需要使用UnityContainer.Resolve解析对象。你不能依靠WPF来为你做这件事。

相关问题