Ninject通过泛型类型自动解析

时间:2013-11-02 17:01:45

标签: c# dependency-injection ninject inversion-of-control

我们使用Ninject进行依赖注入。我们正在使用我们的自由格式解释的DDD设计我们的代码,其中域对象是IThing。

在以下代码中,如何使用IThing实例获取IThingControl?

interface IThing {}
class Thing : IThing {}

interface IThingControl<T> where T:IThing {}
class ThingControl<Thing> {}

class Module : NinjectModule {
    public override void Load() {
        Bind<IThingControl<Thing>>().To<ThingControl>();
    }
}

class SomewhereInCode {
    void AddControls() {
        List<IThing> things = new List<IThing> {
            new Thing()
        };
        foreach (IThing thing in things) {
            IThingControl<IThing> control = _kernel.Get(); // <----- eh?
            this.Controls.Add(control);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您可以使用MakeGenericTypehere)获取实例,但无法将其投放到IThingControl<IThing>

interface IThing { }
class Thing1 : IThing { }
class Thing2 : IThing { }
interface IThingControl<T> where T : IThing { }
class ThingControl<Thing> { }

class Module : NinjectModule {
    public override void Load()
    {
        Bind(typeof(IThingControl<>)).To(typeof(ThingControl<>));
    }
}

[TestFixture]
public class SomewhereInCode
{
    [Test]
    public void AddControls()
    {
        IKernel kernel = new StandardKernel(new Module());
        List<IThing> things = new List<IThing> { new Thing1(), new Thing2() };
        Type baseType = typeof(IThingControl<>);

        foreach (IThing thing in things)
        {
            Type type = baseType.MakeGenericType(thing.GetType());
            dynamic control = kernel.Get(type);
            Assert.That(
                control is IThingControl<IThing>,
                Is.False);
        }
    }
}

答案 1 :(得分:0)

如果您的目标是从接口到其域对象检索通用控制器,我会重新审视您的设计。

Ninject与通用域类型作为接口不能很好地兼容。这是由于泛型类型的无变量:Ninject - Managing Inconvariance of generic types?