2012-07-27 108 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<>)); 

如果你想坚持对于绑定特定的封闭类型,我不知道比已有的更好的机制(除非可以使用约定扩展)。