Wpf 如何在运行时在Prism中注入新实例?

Wpf 如何在运行时在Prism中注入新实例?,wpf,unity-container,prism,Wpf,Unity Container,Prism,我在WPF应用程序中使用Prism 7.1。 我尝试使用内置IOCUnity,但我不知道如何在运行时解析新实例,可能是从方法或containerProvider。但似乎IContainerProvider不能被注入到我的视图模型中。我有什么选择吗 我想这样做来重新加载我的数据库上下文。有人告诉我,创造新的环境是最容易的 public class ProjectViewModel : BindableBase { private UnitOfWork unitOfW

我在WPF应用程序中使用Prism 7.1。 我尝试使用内置IOCUnity,但我不知道如何在运行时解析新实例,可能是从方法或containerProvider。但似乎IContainerProvider不能被注入到我的视图模型中。我有什么选择吗

我想这样做来重新加载我的数据库上下文。有人告诉我,创造新的环境是最容易的

    public class ProjectViewModel : BindableBase
    {
        private UnitOfWork unitOfWork;
        private IContainerProvider containerProvider;
        private IEventAggregator eventAggregator;
        #region Constructor
        public ProjectViewModel(UnitOfWork unitOfWork, IContainerProvider cp, IEventAggregator ea)
        {
            this.unitOfWork = unitOfWork;
            containerProvider = cp;
            eventAggregator = ea;
            eventAggregator.GetEvent<SendReloadDataEvents>().Subscribe(Reload);
            Reload();
        }
        #endregion

        private void Reload()
        {
            this.unitOfWork = containerProvider.Resolve<UnitOfWork>();
            Projects = new ObservableCollection<Projects>(unitOfWork.ProjectRepo.GetAll());
            Customers = new ObservableCollection<Customers>(unitOfWork.CustomerRepo.Find(x => x.Projects.Count > 0));
            SelectedProjectType = null;
        }
//Other logic continues
}

注入容器是一种反模式,因此我们将尝试避免这种情况,而是注入工厂。事实上,出于这个原因,IContainerProvider和IContainerRegistry没有自己注册,从而无法注入它们

但工厂很容易:

public class ProjectViewModel : BindableBase
{
    private UnitOfWork unitOfWork;
    private Func<UnitOfWork> unitOfWorkFactory;
    private IEventAggregator eventAggregator;
    #region Constructor
    public ProjectViewModel(Func<UnitOfWork> unitOfWorkFactory, IEventAggregator ea) // no need to inject a unit of work
    {
        _unitOfWorkFactory = unitOfWorkFactory;
        eventAggregator = ea;
        ea.GetEvent<SendReloadDataEvents>().Subscribe(Reload); // prefer the parameter
        Reload();
    }
    #endregion

    private void Reload()
    {
        this.unitOfWork = _unitOfWorkFactory(); // create a new one here (the container does the work but is hidden)
        Projects = new ObservableCollection<Projects>(unitOfWork.ProjectRepo.GetAll()); // I'd rather update the existing collection
        Customers = new ObservableCollection<Customers>(unitOfWork.CustomerRepo.Find(x => x.Projects.Count > 0)); // same here, or probably, it could just be IEnumerable
        SelectedProjectType = null;
    }
//Other logic continues
}

请注意,此Func工厂仅适用于最简单的情况。如果需要将参数传递到产品构造函数中,则必须按照所述自行编写代码。还要注意的是,除了配置容器的地方,容器不会出现在任何地方,使代码依赖于容器是不必要的,这会使测试更加难看。

谢谢您的回答。我对Func工厂不熟悉。如何在容器Prism中注册Func工厂?通常我们使用方法containerRegistry.Register;。我认为我不能用Func来代替类…Unity会自动创建Func。只需注册您的类型并注入Func,您就可以获得延迟解析,当然也可以使用接口,即containerRegistry.register;->公共消费者功能注入工厂好的。太棒了。现在我知道它是怎么工作的了。非常感谢你,豪金格。祝你有美好的一天。