2010-01-15 47 views
0

關於StructureMap和泛型的SO有幾個問題,我已經閱讀了一些關於它的博客文章,但我仍然在努力想出解決這個特定場景的解決方案。在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>嗎?

更新:

讀過理查德我已經意識到我原來的問題沒有表達我的問題很好最初反應(這是星期五畢竟!)。我正在處理的不僅僅是ILookup的一個實現,並且希望能夠爲我提供的類型獲取正確的ILookupRepository。我已經更新了上面的問題,希望更準確地反映我的要求。

更新2:

當務之急破解這已經過去了,我們已經採取了略有不同的方法。不過,我仍然有興趣聽取Richard的更多建議。

回答

1

[編輯爲最初的反應沒有回答,真正的問題]

當我需要做同樣的事情,我用命名實例。不幸的是,我想不出任何簡單的方法來做你所需要的,而不會引入非泛型接口。非通用接口應該是這樣的(並會希望不是實際上是公共的):

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接口提供了確定類型的機制。例如。具體Tenant(或從它繼承的任何東西)將返回「ITenant」,允許在適用時重用相同的查找存儲庫。

現在有幫助嗎?

+0

感謝您的回覆。我想我應該比我的問題更清楚,因爲這不利於我。我會用更多信息更新我的問題。 – 2010-01-15 18:06:01

+0

我也更新了我的答案......我對此並不滿意(可能有更好的解決方案),但它可能會指向正確的方向。 – 2010-01-15 19:05:53

+0

這確實給了一些思考,謝謝。 – 2010-01-16 00:02:02