【问题标题】:Can I get instance dynamically by type or class name using Ninject我可以使用 Ninject 按类型或类名动态获取实例吗
【发布时间】:2018-07-20 06:41:13
【问题描述】:
void Start () {
    IKernel nKernel = new StandardKernel();
    nKernel.Bind<IAnimal>().To(typeof(Dog)).Named("Dog");
    nKernel.Bind<IAnimal>().To(typeof(Cat)).Named("Cat");

    IAnimal animalInst = nKernel.Get<IAnimal>("Dog");
    Debug.LogError($"{animalInst.Name}");
    IAnimal  animalInst2 = nKernel.Get<IAnimal>("Cat");
    Debug.LogError($"{animalInst.Name}");
}

我想在运行时动态实例化 IAnimal 的子类,我试图运行这段代码,但它发生错误 "IAnimal animalInst2 = nKernel.Get("Cat");" => ActivationException:错误激活浮动 没有匹配的绑定可用,并且该类型不可自绑定。 如何在一个接口上绑定子类?我可以通过类类型或类名来获取它吗?

【问题讨论】:

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


    【解决方案1】:

    您的Cat 类似乎有一个带有float 参数的构造函数。 Ninject 无法解决这种依赖关系,因为值类型不是自绑定的。

    您可以将.WithConstructorArgument 添加到您的绑定中:

    nKernel.Bind<IAnimal>().To(typeof(Cat))
        .WithConstructorArgument("myFloatArgName", 0)
        .Named("Cat");
    

    或者看看使用provider

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 2022-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2014-10-09
      相关资源
      最近更新 更多