【问题标题】:Why can't I use Get<ClassNameOfConcreteInstance> as a method name in Ninject Extension Factory?为什么我不能在 Ninject Extension Factory 中使用 Get<ClassNameOfConcreteInstance> 作为方法名称?
【发布时间】:2014-03-10 18:11:09
【问题描述】:

看这个非常简单的例子:调用 CreateCar 成功,调用 GetCar 失败,说“激活 ICar 时出错:没有匹配的绑定可用,并且类型不能自绑定”

  public interface ICar { }

  public class Car : ICar
  {
    public Car(string carType) { }
  }

  public interface ICarFactory
  {
    ICar CreateCar(string carType); // this is fine
    ICar GetCar(string carType);    // this is bad
  }

  public class CarModule : NinjectModule
  {
    public override void Load()
    {
      Bind<ICarFactory>().ToFactory();
      Bind<ICar>().To<Car>();
    }
  }

  public class Program
  {
    public static void Main()
    {
      using (var kernel = new StandardKernel(new FuncModule(), new CarModule()))
      {
        var factory = kernel.Get<ICarFactory>();
        var car1 = factory.CreateCar("a type");
        var car2 = factory.GetCar("another type");
      }
    }
  }

假设它必须与 Get*ClassName* 的某种约定相关(类似于 NamedLikeFactoryMethod 的东西)。有没有办法避免应用这个约定?我不需要它,我也不想要它(我已经浪费了太多时间试图找出绑定失败的原因,幸运的是我在 10 家工厂中的 1 家打错了字,我注意到它工作只是因为工厂方法名称是“Ger”而不是“Get”)。

谢谢!

【问题讨论】:

    标签: ninject naming-conventions factory ninject-extensions


    【解决方案1】:

    是的,有一个convention,其中Get 用于使用命名绑定获取实例。工厂扩展为您生成代码,因此您不必为工厂创建样板代码。如果您不想使用,则无需使用它。

    但如果你这样做,你就必须遵守它的约定。使用 Create 构建实例并使用 Get 通过命名绑定检索实例。

    所有这些都记录在wiki中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 2023-01-01
      相关资源
      最近更新 更多