Я пытаюсь проверить функцию составления одного экземпляра MEF.Экспорт происходит с [PartCreationPolicy(CreationPolicy.Shared)]
, а импорт происходит как [ImportMany(typeof(IPartOfThePuzzle), RequiredCreationPolicy = CreationPolicy.Shared)]
.
Я выполнял тест и импортировал одну и ту же деталь из двух разных классов в консольном приложении.Однако два экземпляра реализации IPartOfThePuzzle не кажутся одинаковыми.Похоже, что MEF повторно создает объект во втором вызове.
Ниже приводится то, что у меня есть.
Part1.DLL:
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IPartOfThePuzzle))]
class Piece1 : IPartOfThePuzzle
{
string _prop1;
public string SomeProp { get => _prop1; set => _prop1 = value; }
public Piece1()
{
Console.WriteLine("Piece1 instantiated, setting Prop value to 'First Part " +
"Original Value'");
_prop1 = "First Part Original Value";
}
}
Part2.DLL:
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IPartOfThePuzzle))]
class Piece2 : IPartOfThePuzzle
{
string _prop1;
public string SomeProp { get => _prop1; set => _prop1 = value; }
public Piece2()
{
Console.WriteLine("Piece2 instantiated, setting Prop value to 'Second Part " +
"Original Value'");
_prop1 = "Second Part Original Value";
}
}
Console.exe> GetParts.cs
public class GetParts
{
[ImportMany(typeof(IPartOfThePuzzle))]
public IPartOfThePuzzle[] Pieces { get; set; }
public GetParts()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(
new DirectoryCatalog(
@"C:\PuzzlePieces"
)
);
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
Console.exe> GetPartsAgain.cs
public class GetPartsAgain
{
[ImportMany(typeof(IPartOfThePuzzle))]
public IPartOfThePuzzle[] Pieces { get; set; }
public GetPartsAgain()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(
new DirectoryCatalog(
@"C:\PuzzlePieces"
)
);
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
и, наконец, Console.exe> Программа.cs
static void Main(string[] args)
{
GetParts firstImport = new GetParts();
Console.WriteLine($"Initial value from First Import: {firstImport.Pieces[0].SomeProp}");
firstImport.Pieces[0].SomeProp = "First Import Overwritten Value";
Console.WriteLine($"Overwritten from First Import: {firstImport.Pieces[0].SomeProp}");
Console.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - -");
GetPartsAgain secondImport = new GetPartsAgain();
Console.WriteLine($"Value from Second Import: {secondImport.Pieces[0].SomeProp}");
Console.ReadLine();
}
Вывод на консоль:
Вывод показывает, что Pieces были созданы оба раза (один раз для GetParts и один раздля GetPartsAgain).Документация, блоги и онлайн-форумы говорят, что это был способ предотвратить множественные случаи, но я думаю, что что-то упустил в моем понимании.Можете ли вы помочь мне понять, что это такое?