Search code examples
c#ninjectninject-extensions

How to use Ninject's NamedLikeFactoryMethod with parameters correctly?


I have a C# Console application in which i use Ninject.

If I run it with the following code, the console says: "A Dog with the name Dogy was created, he is 7 years old".

This result is actualy fine to me since i passed 7 as a parameter in the Main()- method in Program.cs, but it feels like i dont use the Extension method "NamedLikeFactoryMethod" propperly in my "PettModul.cs" class since i can type in any string and integer as parameter and the result is still the same. Do i use the "NamedLikeFactoryMethod" wrong? If so, how do i use it propperly?

I Have the following code:

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel();
        kernel.Load(new TierModul());
        var factory = kernel.Get<IPetFactory>();
        var dogy = factory.GetDog("Dogy",7);            
        Console.ReadLine();
    }
}

Dog.cs

public class Dog: IPet
{
    private readonly string _name;
    private readonly int _age;        

    public Dog(string name, int age)
    {
        _age= age;
        _name = name;
        Console.WriteLine($"A Dog with the name {_name} was created, he is{_age} years old");
    }
}

IPetFactory.cs

 public interface IPetFactory
{
    IPet GetDog(string name, int age);
    IPet GetCat(string name);
}

PetModul.cs

public class PetModul : NinjectModule
{
    public override void Load()
    {            
        Bind<IPet>().To<Dog>().NamedLikeFactoryMethod((IPetFactory f) => f.GetDog("name",1));           

        Bind<IHaustierFactory>().ToFactory();
    }
}

Solution

  • That's because

    Bind<IPet>().To<Dog>().NamedLikeFactoryMethod((IPetFactory f) => f.GetDog("name",1))
    

    is equivalent to:

    Bind<IPet>().To<Dog>().Named("Dog")
    

    Ninject's convection is that once you name your factory method with 'Get' prefix, than this method goes for binding named as the rest of this method.

    NamedLikeFactoryMethod is here just to avoid any hardcoded strings.