使用列表集中管理类型映射

本文关键字:类型 映射 管理 集中 列表 | 更新日期: 2023-09-27 18:24:06

我有一堆类型映射,需要在Install方法中注册并在Uninstall方法中删除。目前我的代码如下:

安装:

var serviceLocatorConfig = new ServiceLocatorConfig();
serviceLocatorConfig.RegisterTypeMapping<IListItemRepository, ListItemRepository>();
serviceLocatorConfig.RegisterTypeMapping<ITaskRepository, TaskRepository>();
serviceLocatorConfig.RegisterTypeMapping<IIssueRepository, IssueRepository>();
...

卸载:

var serviceLocatorConfig = new ServiceLocatorConfig();
serviceLocatorConfig.RemoveTypeMapping<IListItemRepository>(null);
serviceLocatorConfig.RemoveTypeMapping<ITaskRepository>(null);
serviceLocatorConfig.RemoveTypeMapping<IIssueRepository>(null);
...

并且这些对于更多的映射继续。

我不喜欢这里的一点是,当我添加一个新的存储库时,我必须在安装方法和卸载方法中都添加一行新行。我想要的是类似的东西

    private readonly Dictionary<Type, Type> _typeMappings = new Dictionary<Type, Type>
                                             {
                                                 {typeof(IListItemRepository), typeof(ListItemRepository)},
                                                 {typeof(ITaskRepository), typeof(TaskRepository)},
                                                 {typeof(IIssueRepository), typeof(IssueRepository)},
                                                 ...
                                             };

然后对于我的安装和卸载方法,我可以迭代集合。。。

foreach (KeyValuePair<Type, Type> mapping in _typeMappings)
{
    serviceLocatorConfig.RegisterTypeMapping<mapping.Key, mapping.Value>();                
}

foreach (KeyValuePair<Type, Type> mapping in _typeMappings)
{
    serviceLocatorConfig.RemoveTypeMapping<mapping.Key>(null);                
}

当我添加更多的存储库时,我只需要更新_typeMappings集合,而不必担心更新这两个方法。

问题是,foreach主体中的RegisterTypeMapping方法抱怨它需要名称空间或类型的名称。我也试过

serviceLocatorConfig.RegisterTypeMapping<typeof(mapping.Key), typeof(mapping.Value)>();

也是,但它也不喜欢。

有什么想法吗?

[EDIT]RegisterTypeMapping方法签名定义在下方

public void RegisterTypeMapping<TFrom, TTo>() where TTo : TFrom, new()
{
   ...
}

使用列表集中管理类型映射

您正试图使用RegisterTypeMapping的通用版本,而您实际上想要的是普通版本:

serviceLocatorConfig.RegisterTypeMapping(mapping.Key, mapping.Value);

编辑:

如果只有泛型版本可供您使用,我认为您可以使用反射&MakeGenericMethod()(完全未经测试!)

serviceLocatorConfig.GetType().GetMethod("RegisterTypeMapping").MakeGenericMethod(new Type[] { mapping.Key, mapping.Value}).Invoke(serviceLocatorConfig, null);