2013-02-05 60 views
3

考慮以下strucure註冊對象與Autofac 3.0.0:在註冊具體類型實現變通用接口隨着Autofac

class Something 
{ 
    public int Result { get; set; } 
} 

class SomethingGood : Something 
{ 
    private int _good; 
    public int GoodResult { 
     get { return _good + Result; } 
     set { _good = value; } 
    } 
} 

interface IDo<in T> where T : Something 
{ 
    int Calculate(T input); 
} 

class MakeSomethingGood : IDo<SomethingGood> 
{ 
    public int Calculate(SomethingGood input) { 
     return input.GoodResult; 
    } 
} 

class ControlSomething 
{ 
    private readonly IDo<Something> _doer; 
    public ControlSomething(IDo<Something> doer) { 
     _doer = doer; 
    } 

    public void Show() { 
     Console.WriteLine(_doer.Calculate(new Something { Result = 5 })); 
    } 
} 

我試圖註冊具體類型MakeSomethingGood然後通過逆變界面解決它。

var builder = new ContainerBuilder(); 
builder.Register(c => new MakeSomethingGood()).As<IDo<SomethingGood>>(); 
builder.Register(c => new ControlSomething(c.Resolve<IDo<Something>>())).AsSelf(); 

var container = builder.Build(); 
var controller = container.Resolve<ControlSomething>(); 

...和Resolve因爲發現IDo<Something>

什麼我做錯了任何組件出現故障?

謝謝

+0

[Customizing Autofac's component resolution/Issue with generic co-/contravariance]可能的重複(http://stackoverflow.com/questions/7010236/customizing-autofacs-component-resolution-issue-with-generic-co-contravarian ) – Steven

+0

另一個問題中提到的ContravariantRegistrationSource在3.0.0中仍然可用。 –

+0

@Steven - 這是非常相似,但我想在這裏問不同的問題。 – ZENIT

回答

1

您註冊一個IDo<SomethingGood>並嘗試解決一個IDo<Something>。那該如何運作?爲此,IDo<T>應定義爲協變:IDo<out T>

由於IDo<in T>定義爲逆變(使用in關鍵字),因此不能簡單地將IDo<SomethingGood>指定爲IDo<Something>。這不會在C#編譯:

IDo<SomethingGood> good = new MakeSomethingGood(); 

// Won't compile 
IDo<Something> some = good; 

這就是爲什麼Autofac解決不了它,甚至與ContravariantRegistrationSource

相關問題