本文介绍了如何动态实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个工厂类,该工厂类将为我提供不同DbContext的单例化实例。
I am trying to build a factory class that will feed me singleton-ized instances of different DbContexts.
主要思想是使 Dictionary< Type,DbContext>
将容纳我需要的所有实例,以及 GetDbContext(Type type)
方法,该方法在字典并返回(如果已存在)。如果没有,则应该创建一个新的Type()并将其添加到相应的字典中。
The main idea is to have a Dictionary<Type,DbContext>
that will hold all the instances I need , and a GetDbContext(Type type)
method that looks up type in the dictionary and returns it if it already exists. If it doesn't it should create a new Type(), and add it to the corresponding dictionary.
我不知道该怎么做 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];
}
}
推荐答案
制作它是一种通用方法:
Make it a generic method:
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];
}
这篇关于如何动态实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!