在构造函数之外访问容器
Access container outside of constructor
使用 Unity,我可以通过构造函数注入各种 controls/interfaces,如下所示:
private readonly IEmployeeRepository _employeeRepository;
public EmployeeView_EmployeeListViewModel(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
但是,我需要在构造函数之外访问特定控件(比如示例中使用的控件)(我无法编辑构造函数)。
有没有办法,怎么做?
编辑
更多信息 - 我有一个 DataForm,它允许用户在他们的 DataGrid(简单编辑表单)上执行简单的 CRUD 操作。此控件来自 Telerik inc.,因此它的命令 class 如下所示:
public class CustomDataFormCommandProvider : DataFormCommandProvider
{
public CustomDataFormCommandProvider():base(null)
{
}
protected override void MoveCurrentToNext()
{
if (this.DataForm != null)
{
this.DataForm.MoveCurrentToNext();
this.DataForm.BeginEdit();
}
}
protected override void MoveCurrentToPrevious()
{
if (this.DataForm != null)
{
this.DataForm.MoveCurrentToPrevious();
this.DataForm.BeginEdit();
}
}
protected override void CommitEdit()
{
if (this.DataForm != null && this.DataForm.ValidateItem())
{
this.DataForm.CommitEdit();
}
}
protected override void CancelEdit()
{
if (this.DataForm != null)
{
this.DataForm.CancelEdit();
}
}
}
如果我以任何方式更改构造函数,命令将停止工作(因此我无法将我的接口放入构造函数)。
我需要做的,在CommitEdit
下,除了更新用户控件,我还想做一个单独的调用,它将特定用户的更改保存在数据库下(我的IEmployeeRepository
照顾所有)。
这就是为什么我需要找到一种方法,如何实现这种 'proper' 方式。我当然可以重新设计此控件的模板样式并重新绑定“确定”和“取消”按钮,但我不认为这是可行的方法。
决赛
ServiceLocator
完成了任务。这是代码:
_employeeRepository = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IEmployeeRepository>();
有ServiceLocator.Current.GetInstance
可以随时随地为您提供任何依赖。
但要小心,因为依赖关系几乎是隐藏的。
使用 Unity,我可以通过构造函数注入各种 controls/interfaces,如下所示:
private readonly IEmployeeRepository _employeeRepository;
public EmployeeView_EmployeeListViewModel(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
但是,我需要在构造函数之外访问特定控件(比如示例中使用的控件)(我无法编辑构造函数)。
有没有办法,怎么做?
编辑 更多信息 - 我有一个 DataForm,它允许用户在他们的 DataGrid(简单编辑表单)上执行简单的 CRUD 操作。此控件来自 Telerik inc.,因此它的命令 class 如下所示:
public class CustomDataFormCommandProvider : DataFormCommandProvider
{
public CustomDataFormCommandProvider():base(null)
{
}
protected override void MoveCurrentToNext()
{
if (this.DataForm != null)
{
this.DataForm.MoveCurrentToNext();
this.DataForm.BeginEdit();
}
}
protected override void MoveCurrentToPrevious()
{
if (this.DataForm != null)
{
this.DataForm.MoveCurrentToPrevious();
this.DataForm.BeginEdit();
}
}
protected override void CommitEdit()
{
if (this.DataForm != null && this.DataForm.ValidateItem())
{
this.DataForm.CommitEdit();
}
}
protected override void CancelEdit()
{
if (this.DataForm != null)
{
this.DataForm.CancelEdit();
}
}
}
如果我以任何方式更改构造函数,命令将停止工作(因此我无法将我的接口放入构造函数)。
我需要做的,在CommitEdit
下,除了更新用户控件,我还想做一个单独的调用,它将特定用户的更改保存在数据库下(我的IEmployeeRepository
照顾所有)。
这就是为什么我需要找到一种方法,如何实现这种 'proper' 方式。我当然可以重新设计此控件的模板样式并重新绑定“确定”和“取消”按钮,但我不认为这是可行的方法。
决赛
ServiceLocator
完成了任务。这是代码:
_employeeRepository = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IEmployeeRepository>();
有ServiceLocator.Current.GetInstance
可以随时随地为您提供任何依赖。
但要小心,因为依赖关系几乎是隐藏的。