[英]Constructor Injection of an ObjectContext using Unity/Prism/MVVM
我使用带有MVVM模式和Prism的WPF开发了一个应用程序。 视图将添加到ModuleCatalog中,并且视图模型将注册到统一容器。 为此,我正在使用一个负责创建shell的Bootstrapper,配置统一容器和模块目录。
现在的问题是,如何将我的EntityContext注入到几个视图模型中。
首先是Bootstrapper:
public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
Shell shell = Container.Resolve();
shell.Show();
return shell;
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<EntityContext >("Context");
Container.RegisterType<PersonViewModel>(new InjectionConstructor(
new ResolvedParameter<EntityContext >("Context")));
}
protected override IModuleCatalog GetModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(PersonModule));
return catalog;
}
viewmodel看起来像那样(摘录)
public class PersonViewModel : ViewModelBase, IDataErrorInfo
{
private Person _person;
private PersonRepository _repository;
readonly EntityContext _context;
public PersonViewModel(EntityContext context)
{
_context = context;
_person = new Person();
_repository = new PersonRepository(context);
}
模块:
public class PersonModule : IModule
{
private readonly IRegionManager regionManager;
public PersonModule(IRegionManager regionManager)
{
this.regionManager = regionManager;
}
public void Initialize()
{
regionManager.RegisterViewWithRegion("PersonData", typeof(PersonView));
}
}
代码隐藏视图:
public partial class PersonView : UserControl
{
private PersonViewModel _vm;
public PersonView()
{
InitializeComponent();
}
[Dependency]
public PersonViewModel VM
{
get
{
return this.DataContext as PersonViewModel;
}
set
{
_vm = value;
this.DataContext = _vm;
}
}
}
我不确定我的方法原则上是否正常工作,但为了保存对数据库的更改,我需要了解我所做的更改。
现在它显然不起作用, 因为发生了ModuleInitializeException 。
堆栈跟踪:
1.FindLongestConstructor(Type typeToConstruct)
bei Microsoft.Practices.ObjectBuilder2.ConstructorSelectorPolicyBase
1.FindLongestConstructor(Type typeToConstruct)
bei Microsoft.Practices.ObjectBuilder2.ConstructorSelectorPolicyBase
1.FindLongestConstructor(Type typeToConstruct)
bei Microsoft.Practices.ObjectBuilder2.ConstructorSelectorPolicyBase
1.SelectConstructor(IBuilderContext context)
如果对于这个问题还有其他解决方案,我对它持开放态度,但我想要使用或多或少的基本结构。
提前致谢。
您必须配置容器以消除EntityContext的构造:
Container.RegisterType<EntityContext >("Context", new InjectionConstructor(...))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.