Created
April 17, 2014 10:46
-
-
Save orient-man/10973125 to your computer and use it in GitHub Desktop.
Example of factory with dependencies chosen by factory method name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Ninject; | |
using Ninject.Extensions.Factory; | |
using NUnit.Framework; | |
namespace NInjectFactories | |
{ | |
public interface IFooFactory | |
{ | |
IFoo GetFoo1(); | |
IFoo GetFoo2(); | |
} | |
public interface IFoo { int GetResult(); } | |
public interface IBaz { int GetResult(); } | |
class Baz1 : IBaz { public int GetResult() { return 1; } } | |
class Baz2 : IBaz { public int GetResult() { return 2; } } | |
class Foo : IFoo | |
{ | |
private readonly IBaz baz; | |
public Foo(IBaz baz) | |
{ | |
this.baz = baz; | |
} | |
public int GetResult() | |
{ | |
return baz.GetResult(); | |
} | |
} | |
[TestFixture] | |
public class FactoriesTests | |
{ | |
[Test] | |
public void NamedLikeFactoryMethod() | |
{ | |
var kernel = new StandardKernel(); | |
kernel.Load<FuncModule>(); | |
kernel.Bind<IFooFactory>().ToFactory(); | |
kernel.Bind<IBaz>().To<Baz1>().WhenAnyAncestorNamedLikeFactoryMethod((IFooFactory f) => f.GetFoo1()); | |
kernel.Bind<IBaz>().To<Baz2>().WhenAnyAncestorNamedLikeFactoryMethod((IFooFactory f) => f.GetFoo2()); | |
kernel.Bind<IFoo>().To<Foo>().NamedLikeFactoryMethod((IFooFactory f) => f.GetFoo1()); | |
kernel.Bind<IFoo>().To<Foo>().NamedLikeFactoryMethod((IFooFactory f) => f.GetFoo2()); | |
Assert.That(kernel.Get<IFooFactory>().GetFoo1().GetResult(), Is.EqualTo(1)); | |
Assert.That(kernel.Get<IFooFactory>().GetFoo2().GetResult(), Is.EqualTo(2)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment