Microsoft.Composition (Portable MEF): Attribute Model

2016/02/06

Microsoft.Composition (Portable MEF): Attribute Model

This post is part of mini series, which complete the full MEF series.

The original MEF series goes over the version shipped with the .NET framework.
This mini series will go over the API of 3rd lightweight (yet efficient) MEF version 
which consumed via NuGet.

This version is following the same concept of the previous changes yet some APIs
has been changed.

Apart of the APIs refactoring (mostly for better)
this MEF version is having much better descriptive Exception (it was
really bad on previous versions)

The down side of this version is lack of documentation.
this mini series aims to get you started and get you on track with Microsoft.Composition.
It may be kind of alternative documentation.

Microsoft.Composition is using the same concept like the other MEF versions
but it has some API changes (mostly for the better).

It’s still supporting the [Export] [Import] and [ImportMany] attributes.

but the Container and Fluent API has some changes.

The following code snippet will put you on track with the Attribute based model.

The contracts:

public interface ILogger
{
    void Log(string message);
}

public interface ISetting
{
    ConsoleColor GetColor();
}

Microsoft.Composition has no longer support for [InheritedExport] attribute

The implementation:

[Export(typeof(ILogger))]
[Shared]
public class Logger : ILogger
{
    public void Log(string message) =>
        Console.WriteLine(message);
}
[Export(typeof(ILogger))]
[Shared]
public class ColorLogger : ILogger
{
    [Import]
    public ISetting Setting { get; set; }
    public void Log(string message)
    {
        Console.ForegroundColor = Setting.GetColor();
        Console.WriteLine(message);
        Console.ResetColor();
    }
}

[Export(typeof(ISetting))]
[Shared]
public class TheSetting : ISetting
{
    public ConsoleColor GetColor() =>
        ConsoleColor.Yellow;
}

The default has changed and Shared isn’t the default any more therefore you have to use the [Shared] attribute
which replace the [PartCreationPolicy] attribute.

be aware that Microsoft.Composition is having kind of Bug related to private property
of nested dependency.
As you can see at the CollorLogger class the Setting modifier is sets to public
this is something you don’t usually what to do,
this issue can mitigate by Constructor injection (which will be discuss on latter post).

Some logic (without Export attribute)

public class MyLogic
{
    [ImportMany]
    private ILogger[] Loggers { get; set; }

    [Import]
    private ISetting Setting { get; set; }
    [Import]
    private ISetting Setting1 { get; set; }
    public void Execute()
    {
        Console.WriteLine(Setting.GetHashCode());
        Console.WriteLine(Setting1.GetHashCode());
        foreach (var logger in Loggers)
        {
            logger.Log("MEF");
        }
    }
}

as you can see in this snippet, private property supported in some cases.

And the composition:

var configuration = new ContainerConfiguration()
        .WithAssembly(typeof(Program).Assembly);

using (var container = configuration.CreateContainer())
{

    var logic = new MyLogic();
    container.SatisfyImports(logic);
    logic.Execute();

}

this is how you compose (no equivalent to Directory Catalog)
in the next post we will go deeper into the configuration options,
and cover the Fluent API.

summary

Microsoft.Composition is the better version of MEF in most aspects,
the private property bug is quite annoying (if you’re using the attribute model),
but the overall experience is better.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

5 comments

  1. Marek Ištvánek2016/02/24 ב 15:24

    Will this version of MEF be supported in ASP.NET Core?

    It seams to be abandoned and lacks the proper documentation which You fill in…
    This page does not mention MEF at all, even if it is from Microsoft as well.

    Reply
    1. Bnaya Eshet
      Bnaya Eshet2016/03/06 ב 18:44

      I think you’re right.

      it’s suppose to be a future post but in general you may wan’t to check Autofac
      on version 4 which is still RC they’re adding support to .NET core

      Reply
  2. Marek Ištvánek2016/02/24 ב 15:27

    Is there a way to find out what exports are registered in the container?

    I have come accross this issue while writing Prism 6 UWP MEF library.

    Reply
    1. Bnaya Eshet
      Bnaya Eshet2016/03/06 ב 18:41

      configuration.DiscoveredParts

      Reply
  3. Scott Software2017/10/04 ב 21:20

    Great article and thank you!

    When migrating to MEF 2.0 how do we declare the creation policy as “NonShared”.

    In the framework version of MEF, we used this attribute:

    [PartCreationPolicy(CreationPolicy.NonShared)]

    Is there .net core MEF 2 equivalent for setting the above attribute to ‘NonShared’?

    Reply