本文介绍了与泛型类型的注入变化实现服务定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

public interface IConverter<TValue, TConverted>
{     
}

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

通过一个例子在设置绑定:

With an example binding at setup:

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



所以,我有固定的转换器和没有重复绑定的集合。

So I have a collection of fixed converters and no duplicate bindings.

[问题]
我的问题是我怎么去实施IConverterProvider和注射映射到单身可用绑定的字典?或者换句话说,如何避免运行时服务定位器模式。

[Question]My question is how do I go about implementing the IConverterProvider and injecting a dictionary of available bindings mapped to singletons? Or in other words, how to avoid the run-time service-locator pattern.

目前我只用NInject内核每次来解决,但我相信这个反模式。我想是这样的:

Currently I'm just using the NInject kernel to resolve each time, but I believe this an anti-pattern. What I would like is something like this:

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

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

    public IConverter<TValue, TConverted> GetConverter<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这样的尝试都没有成功。

But this effectively requires that I'm able to resolve and get a list of all IConverter<,> from the dependency injection kernel, and my previous attempts of doing this from NInject haven't been successful.

推荐答案

这是通过的

This is supported by Ninject.Extensions.Factory

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

没有要求实施

重命名 GetConverter CreateConverter 或其他名称不能与获取

Rename GetConverter to CreateConverter or another name not starting with Get

这篇关于与泛型类型的注入变化实现服务定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 17:46