簡體   English   中英

在StructureMap中連接通用接口

[英]Wiring up generic interfaces in StructureMap

因此,關於StructureMap和泛型存在一些問題,我已經閱讀了一些有關它的博客文章,但是我仍在努力尋找針對此特定方案的解決方案。

鑒於:

public interface ILookup
{
}

public interface ISupplier : ILookup
{
}

public interface ITenant : ILookup
{
}

public class Supplier : ISupplier
{
}

public class Tenant : ITenant
{
}

public interface ILookupRepository<TLookup> where TLookup : ILookup
{
   void DoSomethingWith(TLookup lookup);
}

public class LookupRepository<TLookup> : ILookupRepository<TLookup> where TLookup : ILookup
{
   public void DoSomethingWith(TLookup lookup)
   {
      SaveOrWhatever(lookup);
   }
}

public class SomeClass
{   
   public void ProcessLookup(ILookup lookup)
   {
      // Get hold of a concrete class for ILookupRepository<TLookup> where TLookup is the type of the supplied
      // lookup. For example, if ProcessLookup is passed an ISupplier I want a LookupRepository<ISupplier>.
      // If it's passed an ITenant I want a LookupRepository<ITenant>.

      // var repository = ???

      repository.DoSomethingWith(lookup);
   }
}

我如何讓StructureMap為SomeClass.ProcessLookup提供相應的LookupRepository<ISupplier>LookupRepository<ITenant> 沒有反射,這可能嗎? 是否可以替代地獲取LookupRepository<Supplier>LookupRepository<Tenant>

更新:

閱讀了Richard的初步答復后,我意識到我原來的問題並不能很好地表達我的問題(畢竟是星期五!)。 我正在處理的不僅僅是ILookup的一種實現,並且希望能夠為所提供的類型獲取正確的ILookupRepository。 我已經更新了上面的問題,希望可以更准確地反映我的要求。

更新2:

由於我們采取了略有不同的方法,因此破解此刻的迫切需求已經過去。 但是,我仍然有興趣聽取Richard的其他建議。

[編輯為最初的回答沒有回答真正的問題]

當我需要做類似的事情時,我使用命名實例。 不幸的是,如果不引入非通用接口,我想不出任何簡單的方法來完成所需的工作。 非通用接口如下所示(希望實際上不會公開):

public interface ILookupRepository
{
   void DoSomethingWith(object lookup);
}

使ILookupRepository繼承自非通用ILookupRegistry接口。 然后,在StructureMap 2.5.4中,您可以執行以下操作:

 For<ILookupRepository>().Add<LookupRepository<Supplier>>()  
    .Named(typeof(Supplier).FullName);
 For<ILookupRepository>().Add<LookupRepository<Tenant>>()  
    .Named(typeof(Tenant).FullName);

然后使用以下方法在您的方法中獲取查找存儲庫

var repo = ObjectFactory.GetInstance<ILookupRepository>(lookup.GetType().FullName);

注意:如果ILookup接口提供確定類型的機制,可能會更好(如果可能)。 例如,具體的租戶(或從其繼承的任何租戶)將返回“ ITenant”,從而允許在適用時重用相同的查找存儲庫。

現在有幫助嗎?

暫無
暫無

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

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