【发布时间】:2012-07-27 06:22:36
【问题描述】:
警告:我刚刚开始探索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,如果您使用由 Foo 或 Foo
实现的 IFoo 或 IFoo 的典型约定,那么您可以避免设置绑定而只需使用约定基于扩展 - github.com/ninject/ninject.extensions.conventions