locked
Instantiate Extension class in XAML with constructor injection RRS feed

  • Question

  • User60362 posted

    Hi,

    I have created a LocalizeExtension to use in XAML (xmlns:i18n="clr-namespace:OrderCentral.Helpers;assembly=OrderCentral") and it uses a constructror that expects an instance of ILocalize. Everything is registered with the dependency injection service (AutoFac) but it fails to properly locate the ILocalize when to instantiate LocalizeExtension. Resolving the dependency directly from the container works so it has been registered.

    How is the correct way of doing this?

    Thursday, July 16, 2015 11:02 AM

All replies

  • User181 posted

    You can't call non-default constructors from XAML. Typically a XAML-friendly class will have a default constructor and then use public properties to configure them.

    Thursday, July 16, 2015 12:29 PM
  • User131778 posted

    @Adam, you can instantiate objects with non-default constructor with <x:Arguments>. Also described in Charles book chapter.

    @joacar, I found not very practical to make constructor injection for the MVVM-helpers (because they a not generally portable, no XAML-friendly etc) and personally go for Locator pattern if I need take them via DI-container. It is dumb, but easy and works. You also can add additional constructor that accept your dependencies for easer unit-testing if you want to test it.

    ```

    public class LocalizeExtension : IMarkupExtension { public LocalizeExtension() : this(ServiceLocator.Current.GetService()) { }

    public LocalizeExtension(ILocalize localize)
    {
         ...
    }
    
    public string Key { get; set; }
    
    public object ProvideValue(IServiceProvider serviceProvider)
    {
        ...
    }
    

    }

    ```

    Thursday, July 16, 2015 4:11 PM
  • User181 posted

    you can instantiate objects with non-default constructor with . Also described in Charles book chapter.

    You just blew my mind...

    Thursday, July 16, 2015 4:30 PM
  • User76049 posted

    @ylemsoul

    That is awesome.

    Thursday, July 16, 2015 4:35 PM
  • User60362 posted

    @ylemosul That was how I ended up solving it. Will read the link to Charle's book - thanks for that!

    Friday, July 17, 2015 11:27 AM
  • User120789 posted

    @ylemsoul Can you provide a simple example of utilization?

    Sunday, December 18, 2016 12:58 PM