I am trying to build a factory class that will feed me singleton-ized instances of different DbContexts.
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.
I have no idea how to do 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];
}
}