Question

Look at this very simple example: Calling CreateCar it works, calling GetCar it fails, saying "Error activating ICar: No matching bindings are available, and the type is not self-bindable".

  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");
      }
    }
  }

Is assume it must be related to some kind of convention with Get*ClassName* (something like the NamedLikeFactoryMethod stuff). Is there any way to avoid this convention to be applied? I don't need it and I don't want it (I already wasted too much time trying to figure out why the binding was failing, it was just luck that I made a typo in 1 of my 10 factories and I noticed it to work just because the factory method name was "Ger" instead of "Get").

Thanks!

Was it helpful?

Solution

Yes, there is a convention, where the Get is used to obtain instances using a named binding. The factory extension generates code for you so you don't have to create boilerplate code for factories. You don't need to use it, if you don't want to.

But if you do, you are bound to its conventions. Use Create to build instances and Get to retrieve instances via a named binding.

All this is documented in the wiki.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top