2013-07-19 3 views
2

의 종속성 문제를 해결하는 데 문제가 있습니다. 유형에 대한 동등한 차이가있을 수 있습니다.컨테이너에서 올바른 유형을 해결하는 방법 (정적 유형 대 런타임 유형)?

다음 프로그램은 0, 1을 반환합니다. 즉, 두 호출은 동일한 형식을 반환하지 않습니다 (형식을 가져 오는 동일한 개체가있는 경우). 반환 할 것으로 기대합니다. 1,1 . (차이점은, 내 VAR의 정적 타입이 다르다는 것을 실행시의 형태를 사용하는 방법이있다?) 당신은의 런타임 해상도의 일종을 할

감사

IContainer _container; 

void Main() 
{ 
    var builder = new ContainerBuilder(); 
    builder.RegisterType<AHandler>().As<IHandler<A>>(); 
    _container = builder.Build(); 

    IBase a = new A(); 
    Console.WriteLine(Resolve(a)); 
    A b = new A(); 
    Console.WriteLine(Resolve(b)); 
} 

int Resolve<T>(T a) where T:IBase 
{ 
    return _container.Resolve<IEnumerable<IHandler<T>>>().Count(); 
} 

// Define other methods and classes here 
interface IBase{} 
interface IHandler<T> where T:IBase {} 

class A : IBase{} 

class AHandler : IHandler<A>{} 
+0

이 (내가 정적으로 입력 된 솔루션을 찾고 있어요 링크 http://www.dotnetperls.com/dynamic –

+0

참조를 아마도 동적 사용과 다름). – Dave

답변

1

이 필요합니다 유형. 예 : dynamic 키워드를 사용하여 :

IBase a = new A(); 
Console.WriteLine(Resolve((dynamic)a)); 
A b = new A(); 
Console.WriteLine(Resolve((dynamic)b)); 

또는 반사 사용 : 반사를 사용하는 것은 비록

int ResolveDynamic(IBase a) 
{ 
    MethodInfo method = typeof(IContainer).GetMethod("Resolve"); 
    var handlerType = typeof(IHandler<>).MakeGenericType(a.GetType()); 
    var enumerableType = typeof(IEnumerable<>).MakeGenericType(handlerType); 
    MethodInfo generic = method.MakeGenericMethod(enumerableType); 

    var result = (IEnumerable<object>)generic.Invoke(_container, null); 
    return result.Count(); 
} 
+0

흥미 롭군요. 그러나 나는 다른 해결책을 기대하고 있다고 말해야합니다. inst의 ContravariantRegistrationSource에 기반한 것. 이것은 아마도 C#의 일반적인 제한 사항이지만 여전히 해결책을 찾고 있습니다 ... 나는 이것이 int라고 생각합니다. (T a) T : IBase가 잘못된 것 같습니다. – Dave