0

I have a WinUI 3 app where we use Dependency-Injection from Microsoft.Extensions, and settings containing DateTime the current Date-Time formatting have been registered to the service collection as followed:

services.AddSingleton<IDateFormatService, DateFormatService>();

I'd like to just inject it into the constructor of the IValeConverter, but as it is constructed by the XAML the constructor must be empty.

Below is my current converter

public sealed class DateTimeFormatingConverter : DependencyObject, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is not DateTime dateTime)
            return value;

        // return formatted dateTime based on settings formatting string
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

I know other injection libraries can allow this, as I've seen in this post and there for wondered if a likewise solution exist with the Microsoft extensions version.

I know it's a possibility to make a DependencyProperty and in XAML bind it to the dependency injected property in the viewmodel. However im looking into this as it would clean up the code substantially and while also removed multiple requirements from the converter that another developer won't easily know would be required.

Hulabuli
  • 23
  • 5

1 Answers1

0

I'd like to just inject it into the constructor of the IValeConverter, but as it is constructed by the XAML the constructor must be empty.

Correct.

The XAML processor engine doesn't know how to use Microsoft.Extensions to resolve dependencies so if you want to inject your converter with a constructor dependency that you register yourself, you must construct the converter programmatically (and not define it in the XAML markup).

You could for example do this in App.xaml.cs after you have registered the dependencies, e.g.:

this.Resources.Add("myConverter", 
    services.GetRequiredService<DateTimeFormatingConverter>());
mm8
  • 163,881
  • 10
  • 57
  • 88