如何使用字符串名称为通用存储库创建实体类型? [重复]

问题描述 投票:0回答:1

在这里我创建了通用存储库类,我有“TEntity”的名称,我想用该名称访问我的模型(类)

public class GenericRepository<TEntity> : IService<T>,IDisposable where T : class

这是我的通用存储库

我有字符串“客户” 我如何转换它以访问我的模型?

string model = "Customers";
// Convert String To TEntity Type.
GenericRepository<Customers> ctx = new GenericRepository<Customers>()

我的错误是““模型”是可变的,但使用像类型”

Type repositoryType = typeof(GenericRepository<>).MakeGenericType(model);
var repository = Activator.CreateInstance(repositoryType);
c# .net entity-framework entity-framework-core .net-framework-version
1个回答
0
投票

您可以尝试使用

Type.GetType
:

var modelType = Type.GetType("Customers");
Type repositoryType = typeof(GenericRepository<>).MakeGenericType(modelType);

虽然它可能需要程序集限定的类型名称:

如果您知道另一个程序集中的类型的程序集限定名称(可以从

GetType
获取),则可以使用
Type
方法获取另一个程序集中类型的
AssemblyQualifiedName
对象。
GetType
导致加载
typeName
中指定的程序集。

备注:

  1. 我建议为此目标创建一个从字符串到类型的静态字典,即:

    public static class TypeHelper
    {
        public static readonly IReadOnlyDictionary<string, Type> Map = new Dictionary<string, Type>
        {
            { nameof(Customers), typeof(Customers) }
        };
    }
    
  2. 通用存储库/UoW over EF 可以被视为反模式(如果您使用 EF)。

  3. 我认为在通过反射使用运行时构造之前你应该三思而后行。

© www.soinside.com 2019 - 2024. All rights reserved.