我正在尝试构建一个工厂类,它将为我提供不同 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/