2013-10-24 54 views
1

我正在嘗試構建一個工廠類,它將爲我提供不同DbContexts的單例化實例。如何動態實例化對象?

主要想法是有一個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]; 
    } 
} 

回答

3

使它成爲一個通用的方法:

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

'type'是未定義。我認爲你的意思是'typeof(T)'。 –

+0

@Guffa Yeap,多數民衆贊成最簡單的方法來做到這一點。但是什麼是T:New()部分?我從來沒有在 –

+0

之前看到過,如果不是說'where T:new()'我說'T:DbContext'不會在那裏檢查正確的類型會發生什麼? –

2

您可以通過使用Activator創建C#類。一種方法是.CreateInstance(Type type)

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

但是用的DbContext,你很可能要在一個連接字符串傳遞所以使用.CreateInstance(Type type, params Object[] args)

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

或者作爲一種通用的方法:

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