c# - 使用列表集中管理类型映射?

标签 c#

我有一堆类型映射需要在 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)>();

也是,但它也不喜欢那样。

有什么想法吗?

[编辑] 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);

关于c# - 使用列表集中管理类型映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213371/

相关文章:

c# - 如何使用 NHibernate 创建标签系统(多对多)

c# - 消息错误 : System. InvalidCastException:指定的转换无效 10

c# - 我可以发送图像和 rar 文件,但这些文件已被 asp.net 损坏?

c# - Active Directory redirect_uri 显示 IP 而不是 DNS 名称。如何在使用 Azure AD 进行身份验证时在代码中提供绝对 CallbackPath?

c# - 使用 int 参数的 SQL 注入(inject)漏洞

c# - 是否有用于 c# 的流畅电子邮件库?

c# - SQLite.NET - System.NotSupportedException : Cannot compile: Parameter

C#:无法将类型 A 转换为类型 B,其中 A = B

c# - 分组为元素字典

c# - 如何实现类似 "Fences"的东西