我在 Silverlight 5 项目中有一个 IValueConverter 实例,它将自定义数据转换为不同的颜色。我需要从数据库中读取实际的颜色值(因为这些可以由用户编辑)。
由于 Silverlight 使用异步调用通过 Entity Framework 从数据库加载数据,因此我创建了一个简单的存储库,它保存来自 db.xml 的值。
界面:
public interface IConfigurationsRepository
{
string this[string key] { get; }
}
实施:
public class ConfigurationRepository : IConfigurationsRepository
{
private readonly TdTerminalService _service = new TdTerminalService();
public ConfigurationRepository()
{
ConfigurationParameters = new Dictionary<string, string>();
_service.LoadConfigurations().Completed += (s, e) =>
{
var loadOperation = (LoadOperation<Configuration>) s;
foreach (Configuration configuration in loadOperation.Entities)
{
ConfigurationParameters[configuration.ParameterKey] = configuration.ParameterValue;
}
};
}
private IDictionary<string, string> ConfigurationParameters { get; set; }
public string this[string key]
{
get
{
return ConfigurationParameters[key];
}
}
}
现在我想使用 Unity 将我的存储库的这个实例注入到 IValueConverter 实例中......
应用程序.xaml.cs:
private void RegisterTypes()
{
_container = new UnityContainer();
IConfigurationsRepository configurationsRepository = new ConfigurationRepository();
_container.RegisterInstance<IConfigurationsRepository>(configurationsRepository);
}
值转换器:
public class SomeValueToBrushConverter : IValueConverter
{
[Dependency]
private ConfigurationRepository ConfigurationRepository { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((SomeValue)value)
{
case SomeValue.Occupied:
return new SolidColorBrush(ConfigurationRepository[OccupiedColor]);
default:
throw new ArgumentException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
问题是,我在转换器实例中没有得到相同的 Unity-Container(即存储库未注册)。