1

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];
    }
}

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

6 Comments

type is undefined. I think you meant typeof(T).
@Guffa Yeap, thats the simplest way to do it alright. But whats the where T: New() part? I've never seen that before
And what would happen if instead of saying where T: new() I say T: DbContext wouldn't I be checking for the correct type in there?
@ErikPhilips: Yes, I missed changing that one.
|
2

You can create C# classes by using an Activator. One method is the .CreateInstance(Type type).

MyClassBase myClass = Activator.CreateInstance(typeof(MyClass)) as MyClass;

However with a DbContext, you will most likely want to pass in a Connection string so use the .CreateInstance(Type type, params Object[] args)

DbContext myContext = Activator.CreateInstance(typeof(MyClass),
  "ConnectionString") as DbContext;

Or as a Generic method:

if (!_contexts.ContainsKey(typeof(T)))
  _contexts.Add(typeof(T),
    (T)Activator.CreateInstance(typeof(T), "ConnectionString");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.