我想不通这个。我有一个 WPF 应用程序,它使用带有 Unity 构造函数依赖注入的 MVVM 模式。在应用程序中,我使用自定义控件。一开始一切都很好:我将控件添加到我的主窗口,它在 VS 设计器中显示得很好。然后我想让控件做一些有用的事情,为此,它需要一个数据提供者。我决定提供它的最佳方法是将提供程序添加为构造函数中的依赖项。
那是一切都向南走的时候。尽管程序按预期运行,但 VS 设计器无法实例化控件。我构建了一个简单的应用程序来说明我的困境。
MainWindow 后面的代码:
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Unity;
namespace DependencyInjectionDesigner
{
public interface IDependency { }
class Dependency : IDependency { }
class DependentControl : Control
{
public DependentControl()
: this(App.Unity.Resolve<IDependency>()) { }
public DependentControl(IDependency dependency) { }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
主窗口 XAML:
<Window x:Class="DependencyInjectionDesigner.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DependencyInjectionDesigner"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type local:DependentControl}">
<Setter Property="Margin" Value="30"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DependentControl}">
<Border BorderBrush="Green" Background="Gainsboro"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<local:DependentControl/>
</Grid>
</Window>
背后的应用程序代码:
using System.Windows;
using Microsoft.Practices.Unity;
namespace DependencyInjectionDesigner
{
public partial class App : Application
{
public static IUnityContainer Unity { get; private set; }
protected override void OnStartup(StartupEventArgs e)
{
if (Unity != null) return;
Unity = new UnityContainer();
Unity.RegisterType<IDependency, Dependency>(
new ContainerControlledLifetimeManager());
}
}
}
我认为问题在于 VS 设计器在更新控件之前不知道要注册 IDependency 类型。我对么?有没有办法解决这个问题?
我正在使用 VS 2010 Ultimate 和 .Net 4.0。