加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用注入的通用类型变体实现服务定位器

发布时间:2020-12-15 21:47:59 所属栏目:百科 来源:网络整理
导读:我有以下内容: public interface IConverterTValue,TConverted{ }public interface IConverterProvider{ IConverterTValue,TConverted GetConverterTValue,TConverted();} 在安装程序中使用示例绑定: BindIConverterSystem.Int32,System.String().ToInt32T
我有以下内容:

public interface IConverter<TValue,TConverted>
{     
}

public interface IConverterProvider
{
    IConverter<TValue,TConverted> GetConverter<TValue,TConverted>();
}

在安装程序中使用示例绑定:

Bind<IConverter<System.Int32,System.String>>().To<Int32ToStringConverter>();
Bind<IConverter<System.Guid,System.String>>().To<GuidToStringConverter>();

所以我有一组固定的转换器,没有重复的绑定.

[题]
我的问题是如何实现IConverterProvider并注入映射到单例的可用绑定字典?或者换句话说,如何避免运行时服务定位器模式.

目前我只是使用NInject内核来解决每次,但我相信这是一种反模式.我想要的是这样的:

public class ConverterProvider : IConverterProvider
{
    private Dictionary<Type,object> _converters;

    public ConverterProvider(Dictionary<Type,object> converters)
    {
        _converters = converters;
    }

    public IConverter<TValue,TConverted>()
    {
        var fullTypeResolve = typeof (IConverter<,>).MakeGenericType(typeof (TValue),typeof (TConverted));

        return _converters.Where(x => x.Key == fullTypeResolve).Select(x=>x.Value).Cast<IConverter<TValue,TConverted>>().Single();
    }
}

但这实际上要求我能够解析并获得所有IConverter<,>的列表.从依赖注入内核,我之前从NInject做这件事的尝试都没有成功.

解决方法

这得到了 Ninject.Extensions.Factory的支持

Bind<IConverter<System.Int32,System.String>>().To<GuidToStringConverter>();
Bind<IConverterProvider>().ToFactory();

无需实施

将GetConverter重命名为CreateConverter或其他不以Get开头的名称

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读