1

以下のようなオブジェクトがあります。

[Serializable()]
[Export(typeof(IRuleFile))]    
[PartCreationPolicy(CreationPolicy.Shared)]
public class RuleFile : NotifyPropertyChanged, IRuleFile { }

[ImportConstructor]またはを使用する[Import]と、同じオブジェクト参照が返されます。

しかし、プログラムによるアプローチを使用すると、返されるオブジェクトは異なりますが、シングルトンである必要があります。なぜですか?

var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
var exportedObj = container.GetExportedValue<IRuleFile>();

追加した

私のソリューションには2つのビューモデルがあります。以下では1つだけを示していますが、[ImportConstructor]オブジェクトは同じままですが、使用GetExportedValueすると新しいインスタンスが取得され、コンストラクターが再び呼び出されます。

[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public partial class RuleViewModel : ViewModelBase
{
    [ImportingConstructor]
    public RuleViewModel(IRuleFile ruleFile)
    {
        RuleFile = ruleFile; // here the object is fine            
    }

    // this method triggers at the time of loading rule file
    public void LoadRuleState()
    {
        var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        var container = new CompositionContainer(catalog);
        // at this point contructor triggers again in my case
        var exportedObj = container.GetExportedValue<IRuleFile>(); 

        // my intend is to replace the object back in the container after deserialization.
        RuleFile = SerializationHelper.DeserializeFromFile<RuleFile>(Constants.RuleDefinitionPath);
        container.ComposeExportedValue<IRuleFile>(RuleFile);
    }
}

私の実際の意図は、オブジェクトが同じままになるように、逆シリアル化後にオブジェクトを MEF コンテナーに戻すことです。

4

1 に答える 1