Shared Instance
Constructors should not be used to generate shared instances.
What does this mean ?
When a class is marked with Managed Extensibility Framework (MEF) PartCreationPolicy(CreationPolicy.Shared), a single, shared instance of the exported object is generated. As a result, utilizing the constructor to generate new instances makes no sense and will almost always result in unanticipated behavior.
What can happen ?
This rule causes a problem when a constructor of a class designated shared with a PartCreationPolicyAttribute is called.
Recommendation
You should make use of ServiceProvider.GetService(Type) returns the service object of the given 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>();
}
}