1

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.

4

1 回答 1

2

您是要绑定开放的通用版本还是仅基于代码中的“medaData”类型绑定特定的封闭类型?

如果绑定开放类型是意图(或可接受的),那么至少使用 Ninject 3,您应该能够“正常”绑定它们,如下所示:

Bind(typeof(IDataProvider<>)).To(typeof(DataProvider<>));

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

于 2012-07-27T07:55:31.500 回答