I'm trying to create a generic factory I can call to instantiate a class and its dependencies using Ninject constructor injection. It seems to work great, but its not sitting well with me, I don't know if that's because its the first time I've used generics and an IoC container, but I think my approach is flawed. Rather than explain ill just dump my simple test console app.
Farm.cs
class Farm
{
private readonly IAnimal _animal;
private readonly IVehicle _vehicle;
public Farm(IAnimal animal, IVehicle vehicle)
{
_animal = animal;
_vehicle = vehicle;
}
public void Listen()
{
_animal.Speak();
_vehicle.Run();
}
}
program.cs
class Program
{
static void Main(string[] args)
{
var farm = new NinjectFactory<Farm>().GetInstance();
farm.Listen();
Console.Read();
}
}
NinjectFactory.cs
class NinjectFactory<T>
{
public T GetInstance()
{
var kernel = new StandardKernel(new IoCModule());
return kernel.Get<T>();
}
}
NinjectModule.cs
class IoCModule : NinjectModule
{
public override void Load()
{
Bind<IAnimal>().To<Dog>();
Bind<IVehicle>().To<Tractor>();
}
}
Any ideas/feedback would be greatly appreciated, thanks.