简体   繁体   English

Ninject通过泛型类型自动解析

[英]Ninject auto resolve by generic type

We use Ninject for Dependency Injection. 我们使用Ninject进行依赖注入。 We are designing our code using our free-form-interpreted DDD, where a domain object is an IThing. 我们正在使用我们的自由格式解释的DDD设计我们的代码,其中域对象是IThing。

In the following code, how to get an IThingControl using an IThing instance? 在以下代码中,如何使用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);
        }
    }
}

You can get an instance using MakeGenericType ( here ) but you can't cast it to IThingControl<IThing> 您可以使用MakeGenericType此处 )获取实例,但不能将其IThingControl<IThing>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);
        }
    }
}

I would revisit your design if you aim to retrieve a generic controller from an interface to its domain object. 如果您的目标是从接口到其域对象检索通用控制器,我会重新审视您的设计。

Ninject does not play well with generic domain types as interfaces. Ninject不能很好地使用通用域类型作为接口。 This is due to the incovariance of generic types: Ninject - Managing Inconvariance of generic types? 这是由于泛型类型的无效性: Ninject - 管理泛型类型的不一致性?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM