c# - 如何动态实例化对象?

标签 c# entity-framework

我正在尝试构建一个工厂类,它将为我提供不同 DbContext 的单例化实例。

主要思想是有一个Dictionary<Type,DbContext>它将包含我需要的所有实例,以及一个 GetDbContext(Type type)在字典中查找类型并返回它(如果它已经存在)的方法。如果没有,它应该创建一个新的 Type(),并将其添加到相应的字典中。

我不知道该怎么做contexts.Add(type, new type());

public class DbContextFactory
{
    private readonly Dictionary<Type, DbContext> _contexts;
    private static DbContextFactory _instance;

    private DbContextFactory()
    {
        _contexts= new Dictionary<Type, DbContext>();
    }

    public static DbContextFactory GetFactory()
    {
        return _instance ?? (_instance = new DbContextFactory());
    }

    public DbContext GetDbContext(Type type)
    {
        if (type.BaseType != typeof(DbContext))
            throw new ArgumentException("Type is not a DbContext type");

        if (!_contexts.ContainsKey(type))
            _contexts.Add(type, new type()); //<--THIS is what I have now Idea how to do

        return _contexts[type];
    }
}

最佳答案

让它成为一个泛型方法:

public DbContext GetDbContext<T>() where T : new()
{
    if (typeof(T).BaseType != typeof(DbContext))
        throw new ArgumentException("Type is not a DbContext type");

    if (!_contexts.ContainsKey(type))
        _contexts.Add(typeof(T), new T());

    return _contexts[type];
}

关于c# - 如何动态实例化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19555896/

相关文章:

c# - 如何在 C# 中显示方法参数工具提示?

c# - 异常 "String cannot be of Zero length"

c# - Entity Framework : difference between Detach and AsNoTracking

c# - 如何检测当前用户的审计日志?

c# - 新的 Mercosul 牌照正则表达式

c# - 从经过身份验证的 URL 传输音频

c# - 来自 user32.dll 的 DragDetect (IntPtr, Point) 在单声道中是否等效?

c# - 如何将.Net Core应用程序连接到Azure SQL数据库

c# - 使用 linq to sql 将列表附加到数据库

.net - EF4 代码优先 : defining object relationships, 外键