2014-03-30 48 views
0

我正在做一個非常簡單的東西,但不工作。我有,無法將類型'B <A>'隱式轉換爲'B <IA>'?

public class A : IA 
{ 
} 

public interface IA 
{ 
} 

public class B<T> where T : IA 
{ 

} 

現在我使用Autofac註冊此,

 builder.Register<B<IA>>(b => 
     { 
      return new B<A>(); 
     }); 

但我收到此錯誤,

Cannot implicitly convert type 'B<A>' to 'B<IA>'? 

Cannot convert lambda expression to delegate type 'System.Func<Autofac.IComponentContext,B<IA>>' because some of the return types in the block are not implicitly convertible to the delegate return type 

回答

1

給您正在使用的類,它看起來像你只想讓通用參數Register由編譯器決定:

builder.Register(b => new B<A>()); 

B<A>作爲依賴關係的類,然後獲取正確的B<A>實例。對於任何需要將B<IA>作爲依賴的東西沒有任何意義,泛型不能以這種方式工作。如果這就是你想要做的,你需要創建一個接口爲B<T>,而不需要指定任何泛型類型。

所以:

public interface IB 
{ 
} 

public class B<T> : IB where T : IA 
{ 

} 

然後就是需要採取一個依賴於B<T>任何類實際上需要依賴於IB

更新

OpenGenerics在autofac也可以根據您打算如何使用這些類你的幫助。看看the example on their site,這將允許很好地控制通過RegisterGeneric()方法註冊的泛型類型。

相關問題