Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [PartCreationPolicy(CreationPolicy.Shared)]

Tags:

c#

mef

What does [PartCreationPolicy(CreationPolicy.Shared)] mean?

like image 850
Adam Lee Avatar asked Sep 23 '12 23:09

Adam Lee


2 Answers

It means that, when requesting an instance of a class decorated with [PartCreationPolicy(CreationPolicy.Shared)], the CompositionContainer will always return the same instance of this class and not create a new one.

[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
class Foo
{

}

The above class will give the following result:

private void Test()
{
  var foo1 = Container.GetExportedValue<Foo>();
  var foo2 = Container.GetExportedValue<Foo>();
  Console.WriteLine(foo1 == foo2); // => True
}
like image 162
Julien Poulin Avatar answered Nov 15 '22 19:11

Julien Poulin


To add to Julien's answer, I think conceptually you can think of it as a Singleton.

like image 31
sfogle Avatar answered Nov 15 '22 19:11

sfogle