0
votes

In WPF, I can use MEF (System.ComponentModel.Composition) to import dependencies on private properties like this:

[Import]
private IConfigService _service { get; set; }

I'm using MEF through the Microsoft.Composition NuGet package in a UWP application and it works fine if my property is public like this:

 [Import]
 public IConfigService _service { get; set; }

but it doesn't work if I make the property is private. It doesn't throw a CompositionException, it just leaves the property as null. Is there a way to get this working with private properties?

Update

Calling CompositionHost.SatisfyImports on an object successfully resolves its dependencies but not those further down the line. In the example below, calling SatifyImports on the view model will resolve its high level service but the low level service will not be resolved.

[Export]
public class ViewModel
{
    [Import]
    private IHighLevelService _service { get; set; }
}

public interface IHighLevelService { }

[Export(typeof(IHighLevelService))]
public class HighLevelService : IHighLevelService
{
    [Import]
    private ILowLevelService _lowLevelService { get; set; }
}

public interface ILowLevelService { }

[Export(typeof(ILowLevelService))]
public class LowLevelService : ILowLevelService { }
1
Have you called the SatisfyImports method on the created CompositionHost object to have MEF set the` _service` property ? - Nico Zhu - MSFT
Thanks. That helped a bit but it's not the whole answer. Please see the updated question. - Connell.O'Donnell

1 Answers

0
votes

I found a solution that will do for now, though it's not ideal as it has a large reflection overhead. It is a method that uses reflection to find all properties with the import attribute and then calls itself recursively on each of them.

public static class DependencyResolver
{
    public static CompositionHost Container { get; set; }

    public static void SatisfyImports(object arg)
    {
        Container.SatisfyImports(arg);

        var props = arg.GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(p => p.GetCustomAttributes().Contains(new ImportAttribute()));

        foreach (var prop in props)
        {
            object value = prop.GetValue(arg);
            SatisfyImports(value);
        }
    }
}