Skip to content

Instantly share code, notes, and snippets.

@codewithpassion
Last active December 10, 2015 02:09
Show Gist options
  • Save codewithpassion/4365823 to your computer and use it in GitHub Desktop.
Save codewithpassion/4365823 to your computer and use it in GitHub Desktop.
Example of using Ninject Factory Etxtension together with Convention based binding. Based on a question by @JefClaes See as well https://gist.github.com/4363612
using Ninject;
using Ninject.Extensions.Factory;
public interface ICommand
{
void Execute();
}
public interface INameProvider
{
string Name { get; }
}
class NameProvider : INameProvider
{
public string Name
{
get
{
return "World";
}
}
}
public abstract class Command : ICommand
{
public abstract void Execute();
}
public class ConsoleCommand : Command
{
private readonly INameProvider nameProvider;
private readonly string fullName;
public ConsoleCommand(string first, string last, INameProvider nameProvider)
{
this.fullName = string.Format(" {0} {1} ", first, last);
this.nameProvider = nameProvider;
}
public override void Execute()
{
Console.WriteLine("Hello " + this.fullName + this.nameProvider.Name + "!");
}
}
public interface ICommandFactory
{
T Create<T>() where T : ICommand;
ConsoleCommand CreateConsole(string first, string last);
}
class Service
{
private readonly ICommandFactory commandFactory;
public Service(ICommandFactory commandFactory)
{
this.commandFactory = commandFactory;
}
public void DoWork()
{
var cmd = this.commandFactory.CreateConsole("First", "Name");
cmd.Execute();
}
}
class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel();
kernel.Bind<ICommandFactory>().ToFactory();
kernel.Bind<INameProvider>().To<NameProvider>();
kernel.Bind<Service>().ToSelf();
var service = kernel.Get<Service>();
service.DoWork();
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment