Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created January 22, 2013 10:20
Show Gist options
  • Save akimboyko/4593576 to your computer and use it in GitHub Desktop.
Save akimboyko/4593576 to your computer and use it in GitHub Desktop.
Ninject factory with custom naming instance provider
void Main()
{
using(var kernel = new StandardKernel(new CarModule()))
{
kernel.Load<FuncModule>(); // for sake of LinqPAD
var factory = kernel.Get<ICarFactory>();
Assert.That(factory, Is.Not.Null);
var mercedes = factory.CreateCar("Mercedes");
var ferrari = factory.CreateCar("Ferrari");
Assert.That(mercedes, Is.Not.Null.And.InstanceOfType(typeof(Mercedes)));
Assert.That(ferrari, Is.Not.Null.And.InstanceOfType(typeof(Ferrari)));
mercedes.Drive();
mercedes.Stop();
ferrari.Drive();
ferrari.Stop();
}
}
#region ICar implementations
public interface ICar
{
void Drive();
void Stop();
}
public class Mercedes : ICar
{
public void Drive()
{
"Do mercedes drive stuff...".Dump();
}
public void Stop()
{
"Do mercedes stop stuff... ".Dump();
}
}
public class Ferrari : ICar
{
public void Drive()
{
"Do ferrari drive stuff...".Dump();
}
public void Stop()
{
"Do ferrari stop stuff... ".Dump();
}
}
#endregion
public interface ICarFactory
{
ICar CreateCar(string carType);
}
public class CarModule : NinjectModule
{
public override void Load()
{
Bind<ICarFactory>()
.ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
Bind<ICar>()
.To<Mercedes>()
.Named("Mercedes");
Bind<ICar>()
.To<Ferrari>()
.Named("Ferrari");
}
}
public class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider
{
protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments)
{
return (string)arguments[0];
}
protected override ConstructorArgument[] GetConstructorArguments(MethodInfo methodInfo, object[] arguments)
{
return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
}
}
@Lumirris
Copy link

Lumirris commented Apr 8, 2013

@akim thanks for this gist - do you have any experience with Ninject Conventions extension, and how you would write the ICar bindings using that way instead? I posted a question building off this answer - would appreciate any guidance.

@sandeepankundu
Copy link

Changing to IConstructorArgument from ConstructorArgument worked for me.

public class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider
{
protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments)
{
return (string)arguments[0];
}
protected override IConstructorArgument[] GetConstructorArguments(MethodInfo methodInfo, object[] arguments)
{
return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment