2013-10-24 5 views
1

다른 DbContext의 싱글 톤화 된 인스턴스를 제공 할 팩토리 클래스를 작성하려고합니다.어떻게 동적으로 개체를 인스턴스화 할 수 있습니까?

중요한 아이디어는 내가 필요로하는 모든 인스턴스를 보유 할 Dictionary<Type,DbContext>이고, 사전에 유형을 찾고 이미 존재하는 경우이를 반환하는 메서드입니다 (GetDbContext(Type type)). 그렇지 않으면 새 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]; 
} 

답변

3

contexts.Add(type, new type());이 그것을 일반적인 방법을 확인 할 수있는 방법을 모르겠어요. 한 가지 방법은 .CreateInstance(Type type)입니다.

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

'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; 

아니면 일반적인 방법으로를 사용하여 연결 문자열을 전달하는 것이 좋습니다 정의되지 않았습니다. 나는 당신이'typeof (T)'를 의미한다고 생각합니다. –

+0

@ Guffa Yeap, 그건 아주 간단하게하는 가장 간단한 방법입니다. 그러나 T : New() 부분은 어디에 있습니까? 전에는 본 적이 없었습니다 –

+0

그리고'T : new()'내가'T : DbContext'라고 말하는 대신에 올바른 유형을 검사하지 않을 경우 어떻게 될까요? –

2

당신은 Activator를 사용하여 C#을 클래스를 만들 수 있습니다

나는

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]; 
    } 
} 
관련 문제