1
警告:我刚开始探索Ninject。Ninject和绑定仿制药
我定义为这样一个通用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?
感谢您的帮助。
FWIW,如果您使用IFoo或IFoo的典型惯例由Foo或Foo 实现,那么您可以避免设置绑定并使用基于约定的扩展 - https:// github .com/ninject/ninject.extensions.conventions –
2012-07-27 07:47:49
[NInject with Generic interface]的可能重复(http://stackoverflow.com/questions/2216127/ninject-with-generic-interface) – nawfal 2013-11-05 04:49:20