簡體   English   中英

如何在AutoFac中使用接口類型注冊通用接口?

[英]How to register Generic Interfaces with a Interface Type in AutoFac?

我正在嘗試使用Autofac注冊具有多種類型的通用接口,我想打電話:

container.Resolve<Enumerable<IGenericInterface<IInterface>>>(); 

用IInterface類型解決IGenericInterface的所有實現。

我已經嘗試將具有通用接口和具體類的具體類注冊為與Interface的通用接口:

builder.Register(r => new TalkToMeLoud())
    .As<IGenericInterface<Hello>>()
    .As<IGenericInterface<Bye>>()
    .As<IGenericInterface<IInterface>>()
    .InstancePerDependency();

但這會引發錯誤:

Autofac.dll中發生了'System.ArgumentException'類型的未處理異常

附加信息:類型“ TestConsoleApp.TalkToMeLoud”不可分配給服務“ TestConsoleApp.IGenericInterface`1 [[[TestConsoleApp.IInterface,TestConsoleApp,版本= 1.0.0.0,文化=中性,PublicKeyToken =空]]”。

因為這是從Unity到Autofac遷移的一部分,所以我知道這可以由Unity來完成,如下所示:

Container.ResolveAll(typeof(IGenericInterface<IInterface>))

有誰知道如何解決這個問題?

PS:這是我的測試項目

消息很清楚:

無法將類型“ TalkToMeLoud”分配給服務“ IGenericInterface”。

換句話說,您將必須:

  • TalkToMeLoud上實現IGenericInterface<IInterface>
  • 通過將T設置為out參數,使IGenericInterface<T>協變。 IGenericInterface<out T>

CLR將無法施放TalkToMeLoudIGenericInterface<IInterface>即使它可能實現IGenericInterface<Hello>在那里Hello實現IInterface 如果你不熟悉方差的概念,你可能想要做一些谷歌的搜索和念想回答這一個

因此,在您的情況下,您可能需要使接口保持協變。 這使您可以從IGenericInterface<Hello>IGenericInterface<IInterface> 但是,僅當T僅用作接口中的輸出參數時,這才起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM