2012-07-27 107 views
1

警告:我剛開始探索NinjectNinject和綁定仿製藥

我定義爲這樣一個通用domainObject的類:

public abstract class DomainObject<T> : IDomainObject where T : IDomainObject 
{ 
    protected DomainObject(IDataProvider<T> dataProvider) 
    { 
     DataProvider = dataProvider; 
    } 

    // blah and blih 

    protected IDataProvider<T> DataProvider { get; private set; } 
} 

正如你可以在上面的代碼中看到,DomainObject有上表達IDataProvider<T>依賴性的構造。

在我的Ninject模塊中,這裏是我如何做綁定。 元數據從配置存儲檢索並允許我指定要綁定的具體類型。

var medaData = DataContextDictionary.Items[type]; 
var genericDomainObjectType = typeof (DomainObject<>); 
Type[] genericDomainObjectTypeArgs = { medaData.ObjectType }; 
var domainObjectType = genericDomainObjectType.MakeGenericType(genericDomainObjectTypeArgs); 
Bind(domainObjectType).To(medaData.ObjectType); 

var genericIDataProviderType = typeof (IDataProvider<>); 
var iDataProviderType = genericIDataProviderType.MakeGenericType(genericDomainObjectTypeArgs); 
Bind(iDataProviderType).To(medaData.DataProviderType); 

這種運作良好,但我感覺這個代碼是人爲的,並能以更好的方式來寫。

有沒有更好的方式來表達這種依賴與Ninject?

感謝您的幫助。

+1

FWIW,如果您使用IFoo或IFoo 的典型慣例由Foo或Foo 實現,那麼您可以避免設置綁定並使用基於約定的擴展 - https:// github .com/ninject/ninject.extensions.conventions – 2012-07-27 07:47:49

+0

[NInject with Generic interface]的可能重複(http://stackoverflow.com/questions/2216127/ninject-with-generic-interface) – nawfal 2013-11-05 04:49:20

回答

2

你想綁定開放的泛型版本還是僅僅基於代碼中'medaData'類型的特定封閉類型?

如果結合的開放類型爲目的(或接受),那麼至少有Ninject 3,你應該能夠約束他們「正常」,像這樣:

Bind(typeof(IDataProvider<>)).To(typeof(DataProvider<>)); 

如果你想堅持對於綁定特定的封閉類型,我不知道比已有的更好的機制(除非可以使用約定擴展)。