我有一个如下所示的对象。
[Serializable()]
[Export(typeof(IRuleFile))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class RuleFile : NotifyPropertyChanged, IRuleFile { }
使用[ImportConstructor]
or [Import]
,返回相同的对象引用。
但是通过使用编程方法返回的对象是不同的,虽然它应该是单例的,为什么?
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
var exportedObj = container.GetExportedValue<IRuleFile>();
添加
我的解决方案中有两个视图模型,下面我只显示一个,但[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 容器中,以使对象保持不变。