我在一个Silverlight 5项目中有一个IValueConverter实例,它可以将自定义数据转换为不同的颜色。我需要从数据库中读取实际的颜色值(因为这些值可以由用户编辑)。
由于Silverlight使用异步调用通过Entity Framework从数据库加载数据,所以我创建了一个简单的存储库,它保存来自数据库的值。
接口:
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实例中...
App.xaml.cs:
private void RegisterTypes()
{
_container = new UnityContainer();
IConfigurationsRepository configurationsRepository = new ConfigurationRepository();
_container.RegisterInstance<IConfigurationsRepository>(configurationsRepository);
}
IValueConverter:
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容器(即存储库未注册)。