Ninject and binding generics

微笑、不失礼 提交于 2020-01-05 06:55:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!