How to set CreationPolicy singleton in .net-core System.Composition (Mef)

569 views Asked by At

I am converting a DNX project to .net core. Because of dependency changes, I cannot use System.ComponentModel.Composition anymore, instead must use .net core's ported version System.Composition (which I believe is known as MEF 2).

However I could not find an equivalent functionality in MEF2 for setting the CreationPolicy for singleton. In MEF1, the code is

[PartCreationPolicy(CreationPolicy.Shared)]

How can you do this in MEF2?

2

There are 2 answers

0
user3517546 On

Answering own since no answers received although don't have a very good one.

Reading multiple posts, it seems like the Default CreationPolicy is shared, aka singleton. So probably just deleting this line will work.

MEF2 introduced Export Factory, which can be look into to get more details for policy settings.

1
denys-vega On

The solution is to use ConventionBuilder class.

Let's say there are a class called AppShell and it implements the interface IAppShell. In order to export it in shared mode, follow the next steps:

var conventionBuilder = new ConventionBuilder();
conventionBuilder.ForTypesDerivedFrom<IAppShell>()
    .Export<AppShell>()
    .Shared();

Then:

var config = new ContainerConfiguration()
    .WithAssemblies(new[]{ typeof(AppShell).Assembly}, conventionBuilder);