如何使用Unity的Resolve<>()方法将参数发送到对象的构造函数?

时间:2009-08-07 11:19:08

标签: c# dependency-injection unity-container prism cag

在Prism中使用Unity,我想像这样向对象的构造函数发送一个参数:

PSEUDO-CODE:

SmartFormPresenter smartFormPresenter1 =
    this.container.Resolve<SmartFormPresenter(customer)>();

但相反,我必须对其进行实例化然后分配一个属性:

SmartFormPresenter smartFormPresenter1 =
    this.container.Resolve<SmartFormPresenter>();
smartFormPresenter1.ObjectBeingEdited = customer;

有没有办法直接向构造函数发送参数?

1 个答案:

答案 0 :(得分:2)

这是一个很好地回答这个问题的相关问题: Can I pass constructor parameters to Unity's Resolve() method?

如果要执行此操作,唯一的选择是作用域容器。

IUnityContainer subContainer = this.container.CreateScopedContainer();
subContainer.RegisterInstance<Customer>(customer);
smartFormPresenter1 = subContainer.Resolve<SmartFormPresenter>();