Why is this an issue?
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.
This rule raises an issue when a constructor of a class marked shared with a PartCreationPolicyAttribute
is invoked.
Noncompliant code example
[Export(typeof(IFooBar))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class FooBar : IFooBar
{
}
public class Program
{
public static void Main()
{
var fooBar = new FooBar(); // Noncompliant;
}
}
Compliant solution
[Export(typeof(IFooBar))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class FooBar : IFooBar
{
}
public class Program
{
public static void Main()
{
var fooBar = serviceProvider.GetService<IFooBar>();
}
}