ServiceDependencyExtension

Topics: Feature requests
Jun 17, 2012 at 8:22 PM

Hi Geert,

how about adding the following markup extension i use a lot when accessing services from xaml:

xaml example:

<UserControl.Resources>

<catel:ServiceDependency x:Key="CultureManager" x:Type={x:Type Services:ICultureManager} />

</UserControl.Resources>

Here is the code:

   public class ServiceDependencyExtension : MarkupExtension
    {
        public ServiceDependencyExtension()
        {
        }

        public ServiceDependencyExtension(Type type, string name = null)
        {
            this.Type = type;
            this.Name = name;
        }

        [ConstructorArgument("name")]
        public string Name { get; set; }

        [ConstructorArgument("type")]
        public Type Type { get; set; }

         public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Environment.IsInDesignMode)
            {
                return null;
            }

            Contract.Assert(this.Type != null);
            return ServiceLocator.Instance.ResolveType(this.Type, this.Name);
        }

        #endregion
Coordinator
Jun 18, 2012 at 8:15 AM

Looks nice. The only downside is that it is hard to use methods inside bindings, but for properties, this is nice.

Jun 18, 2012 at 12:45 PM

i use it for fast and uncomplicated xaml "service" property bindings only .... (never tried it with any methods ...)

Coordinator
Jun 18, 2012 at 7:02 PM

What is the name? The ServiceLocator in Catel does not support it. Is it the property?

Jun 18, 2012 at 7:57 PM

sorry i copied the wrong (older) code. you can simply dismiss the name property. it was for containers which support to resolve named service instances....

Coordinator
Jun 18, 2012 at 8:28 PM

I already did and released a new beta via NuGet today.