私はこれを理解することはできません。Unityコンストラクターの依存性注入でMVVMパターンを使用するWPFアプリケーションがあります。アプリケーションでは、カスタムコントロールを使用します。最初はすべて順調でした。メインウィンドウにコントロールを追加すると、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();
}
}
}
MainWindow 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タイプを登録することを知らないことだと思います。私は正しいですか?これを回避する方法はありますか?
VS2010Ultimateと.Net4.0を使用しています。