首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Unity将对象注入到IValueConverter实例中

使用Unity将对象注入到IValueConverter实例中
EN

Stack Overflow用户
提问于 2012-04-23 17:36:05
回答 2查看 4.6K关注 0票数 7

我在Silverlight5项目中有一个IValueConverter实例,它可以将自定义数据转换为不同的颜色。我需要从数据库中读取实际的颜色值(因为用户可以编辑这些颜色值)。

由于Silverlight使用异步调用通过实体框架从数据库加载数据,因此我创建了一个简单的存储库,它保存来自数据库的值。

接口:

代码语言:javascript
复制
public interface IConfigurationsRepository
{
    string this[string key] { get; }
}

实现:

代码语言:javascript
复制
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:

代码语言:javascript
复制
private void RegisterTypes()
{
    _container = new UnityContainer();
    IConfigurationsRepository configurationsRepository = new ConfigurationRepository();
    _container.RegisterInstance<IConfigurationsRepository>(configurationsRepository);
}

IValueConverter:

代码语言:javascript
复制
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 (即,存储库未注册)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-23 20:15:27

根据您的评论,您需要使用ServiceLocator来获取ConfigurationRepository的实例,因为转换器的实例不是由Unity创建的,而是由Silverlight/XAML引擎创建的。

所以你的用DependencyAttribute装饰的属性不会被注入。

c#

代码语言:javascript
复制
public class SomeValueToBrushConverter : IValueConverter
{
    public SomeValueToBrushConverter(){
      ConfigurationRepository = ServiceLocator.Current.GetInstance<ConfigurationRepository>();
    }

    private ConfigurationRepository ConfigurationRepository { get; set; }
}

在您的RegisterTypes方法中,您需要配置ServiceLocator:

代码语言:javascript
复制
_container = new UnityContainer();
UnityServiceLocator locator = new UnityServiceLocator(_container);
ServiceLocator.SetLocatorProvider(() => locator);
票数 0
EN

Stack Overflow用户

发布于 2017-01-12 19:18:03

可以使用MarkupExtension解析DI容器中的依赖关系:

代码语言:javascript
复制
public class IocResolver : MarkupExtension
{
    public IocResolver()
    { }

    public IocResolver(string namedInstance)
    {
        NamedInstance = namedInstance;
    }

    [ConstructorArgument("namedInstance")]
    public string NamedInstance { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var provideValueTarget = (IProvideValueTarget)serviceProvider
            .GetService(typeof(IProvideValueTarget));

        // Find the type of the property we are resolving
        var targetProperty = provideValueTarget.TargetProperty as PropertyInfo;

        if (targetProperty == null)
            throw new InvalidProgramException();

        Debug.Assert(Resolve != null, "Resolve must not be null. Please initialize resolving method during application startup.");
        Debug.Assert(ResolveNamed != null, "Resolve must not be null. Please initialize resolving method during application startup.");

        // Find the implementation of the type in the container
        return NamedInstance == null
            ? (Resolve != null ? Resolve(targetProperty.PropertyType) : DependencyProperty.UnsetValue)
            : (ResolveNamed != null ? ResolveNamed(targetProperty.PropertyType, NamedInstance) : DependencyProperty.UnsetValue);
    }

    public static Func<Type, object> Resolve { get; set; }
    public static Func<Type, string, object> ResolveNamed { get; set; }
}

IocResolver必须在应用程序启动期间进行初始化,如下所示:

代码语言:javascript
复制
IocResolver.Resolve = kernel.Get; 
IocResolver.ResolveNamed = kernel.GetNamed;
// or what ever your DI container looks like

之后,您可以在XAML中使用它来在XAML中注入依赖:

代码语言:javascript
复制
<!-- Resolve an instance based on the type of property 'SomeValueToBrushConverter' -->
<MyConverter SomeValueToBrushConverter="{services:IocResolver}" />

<!-- Resolve a named instance based on the type of property 'SomeValueToBrushConverter' and the name 'MyName' -->
<MyConverter SomeValueToBrushConverter="{services:IocResolver  NamedInstance=MyName}" />
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10278044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档