Skip to content

MEF2: Cannot get the same instance with SharedAttribute. #75236

Open
@Wenveo

Description

@Wenveo

Nuget Package: System.Composition v6.0.0

Code:

// See https://aka.ms/new-console-template for more information

using System.Composition;
using System.Composition.Hosting;
using System.Reflection;


var container = new ContainerConfiguration()
    .WithAssembly(Assembly.GetExecutingAssembly())
    .CreateContainer();

var mainApp = container.GetExport<MainApp>();
mainApp.Invoke();

[Shared]
[Export]
class MainApp
{
    readonly ITestServiceImpl testService;

    [ImportingConstructor]
    public MainApp(ITestServiceImpl testService)
    {
        this.testService = testService;
    }

    public void Invoke()
    {
        this.testService.Value = 4;
        this.testService.Initialize();
    }
}

interface ITestItem
{

}

interface ITestService
{
    void PrintValue();
}

interface ITestServiceImpl : ITestService
{
    int Value { get; set; }

    void Initialize();
}

[Shared]
[Export(typeof(ITestServiceImpl)), Export(typeof(ITestService))]
class TestService : ITestServiceImpl
{
    readonly IEnumerable<Lazy<ITestItem>> mefItems;

    public int Value { get; set; }

    [ImportingConstructor]
    public TestService([ImportMany] IEnumerable<Lazy<ITestItem>> mefItems)
    {
        this.mefItems = mefItems;
    }


    public void PrintValue()
    {
        Console.WriteLine(Value);
    }


    public void Initialize()
    {
        foreach (var item in this.mefItems)
        {
            var value = item.Value;
        }
    }
}

[Shared]
[Export(typeof(ITestItem))]
class TestItemA : ITestItem
{
    [ImportingConstructor]
    public TestItemA(ITestService testService)
    {
        testService.PrintValue();
    }
}


[Shared]
[Export(typeof(ITestItem))]
class TestItemB : ITestItem
{
    [ImportingConstructor]
    public TestItemB(ITestService testService)
    {
        testService.PrintValue();
    }
}

Description:
In MainApp.Invoke, The Value has been changed.
But PrintValue always print 0.
image

During debugging, the TestService constructor is called twice (Two instances were created).
The first call is from MainApp, but the second call is from TestItemA?
(MainApp and TestItemA each have two different instances (TestService))
gif

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions