2013-07-19 26 views
2

我在解決中的依賴問題時遇到問題。這可能與類型上的共同/反對差異有關。如何從容器中解析正確的類型(靜態類型vs運行時類型)?

下面的程序返回0,1。這意味着兩個調用來解決不會返回相同的類型(儘管它是相同的對象,用於獲取類型)我期望它返回:1,1 。 (不同的是,靜態類型我的變種不同的是,有沒有使用運行時類型的方法嗎?)

感謝

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

這很有趣,但我不得不說,我期待另一種解決方案。一些基於ContravariantRegistrationSource的inst。這可能是C#泛型的一個限制,但仍然在尋找一個解決方案...我認爲這是在int Resolve (T a)其中T:IBase是錯誤的 – Dave