gpt4 book ai didi

wpf - 使用 MEF 时创建 subview 模型

转载 作者:行者123 更新时间:2023-12-02 20:43:08 25 4
gpt4 key购买 nike

我采用传统的 MVVM 方法,例如,名为“PatientManagementViewModel”的 View 模型由名为“PatientManagementView”的 View 使用。一切都是使用 MEF 注入(inject)的,因此我自己不创建任何实例。

现在假设“PatientManagementViewModel”有一个属性Patient,它是“PatientViewModel”的ObervableCollection。我现在创建“PatientViewModel”实例并传递所选患者的操作如下:

var patientViewModel = _container.GetExportedValue<IPatientViewModel>();
patientViewModel.Patient = patient;

这可行,但是,我想知道这是否有意义。将患者传递给构造函数会更好,因为没有患者就无法存在“PatientViewModel”:

var patientViewModel = new PatientViewModel(patient);

但是我无法使用依赖注入(inject)。

所以问题是:注入(inject) subview 模型是否有意义,或者我应该只注入(inject)主视图模型,并实例化所有 subview 模型而不注入(inject)?

最佳答案

您可以执行以下操作。您可以使用常用的构造函数创建 subview 模型,然后在实例上调用 ComposeParts 来注入(inject)所有内容:

var patientViewModel = new PatientViewModel(patient);
_container.ComposeParts(patientViewModel);

但是由于各种原因每次都这样做并不是很好。为了解决这个场景并封装 MEF 的使用,我创建了一个用于创建 View 模型的帮助服务。它称为 IViewModelFactory,其外观如下:

[Export(typeof(IViewModelFactory))]
[PartCreationPolicy(CreationPolicy.Shared)]
internal class ViewModelFactory : IViewModelFactory
{
[ImportingConstructor]
public ViewModelFactory(CompositionContainer container) {
Contract.Requires(container != null);

Container = container;
}

protected CompositionContainer Container { get; private set; }

public T Create<T>(params object[] args) where T : class {
T result;

try {
bool populateDependencies = false;

if (args == null || args.Length == 0) {
// There are no parameters for contructor, so
// try to create an instance by asking the container.
result = Container.GetExportedValueOrDefault<T>();

if (result == null) {
// The view model is not exported. Just create an instance using reflection
// and then populate all the dependencied using the container.
result = Activator.CreateInstance<T>();
populateDependencies = true;
}
}
else {
// There are constructor parameters. Create an instance using those parameters
// and then populate all the dependencied using the container.
result = (T)Activator.CreateInstance(typeof(T), args);
populateDependencies = true;
}

// Populate dependencies if needed
if (populateDependencies) {
Container.ComposeParts(result);
}

// Initialize the object if applicable
var initializable = result as IInitializable;

if (initializable != null) {
initializable.Initialize();
}
}
catch (Exception ex) {

throw new ViewModelCreationException(
string.Format(
"Unable to create and configure an instance of view model of type {0}. An error occured. See inner exception for details.",
typeof (T)), ex);
}

return result;
}
}

使用这个工厂,您可以创建 subview 模型,如下所示:

var patientViewModel = ViewModelFactory.Create<PatientViewModel>(patient);

这里的缺点是,当您使用构造函数参数时,您会失去对参数类型、计数、顺序等的编译时检查。

关于wpf - 使用 MEF 时创建 subview 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5167352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com