Vishal
Vishal

Reputation: 215

Unity: Dependency Injection

public partial class 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; }
}

Resource Dictionary 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>

I've registered the ICanvasService but it's not getting injected in this class. Resource Dictionary is merged in the xaml file of a windows class:

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

Is there something specific with ResourceDictionary class?

Thanks & Regards, Vishal.

Upvotes: 0

Views: 750

Answers (1)

Jakob Christensen
Jakob Christensen

Reputation: 14956

Your HTCmds object is created by WPF by this line of XAML:

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

WPF has no knowledge of Unity so it does not know how to resolve the dependencies using Unity. You need to resolve objects using UnityContainer.Resolve. You can't rely on WPF to do this for you.

Upvotes: 1

Related Questions