Skip to content

Shared Instance

Shared instances should not be created with constructor

What does this mean ?

Marking a class with PartCreationPolicy(CreationPolicy.Shared), which is part of Managed Extensibility Framework (MEF), means that a single, shared instance of the exported object will be created. Therefore it doesn't make sense to create new instances using the constructor and it will most likely result in unexpected behaviours.

What can happen ?

This rule raises an issue when a constructor of a class marked shared with a PartCreationPolicyAttribute is invoked.

Recommendation

You should use ServiceProvider.GetService(Type) Method to get the service object of the specified type.

Sample Code

Vulnerable :

[Export(typeof(IFooBar))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class FooBar : IFooBar
{
}

public class Program
{
    public static void Main()
    {
        var fooBar = new FooBar(); // Noncompliant;
    }
}

Non Vulnerable :

[Export(typeof(IFooBar))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class FooBar : IFooBar
{
}

public class Program
{
    public static void Main()
    {
        var fooBar = serviceProvider.GetService<IFooBar>();
    }
}

References