问题
Warning: I'm just starting to explore Ninject.
I have a generic DomainObject class defined as this:
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; }
}
As you can see in the code above, that DomainObject
has a constructor expressing the dependency on a IDataProvider<T>
.
In my Ninject module, here is how I do the bindings. metaData is retrieved from a configuration store and allows me to specify the concrete types to bind.
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);
This works well but I have the feeling this code is contrived and could be written in a better way.
Is there a better way to express such a dependency with Ninject?
Thanks for your help.
回答1:
Do you want to bind the open generic version or just the specific closed types based on the 'medaData' type in your code?
If binding the open types is the intent (or acceptable), then at least with Ninject 3, you should be able to bind them 'normally', like so:
Bind(typeof(IDataProvider<>)).To(typeof(DataProvider<>));
If you want to stick with binding specific closed types, I don't know of a better mechanism than what you have already (unless you can use the conventions extension).
来源:https://stackoverflow.com/questions/11682495/ninject-and-binding-generics