TestFromMethod.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using NUnit.Framework;
  3. using Assert = ModestTree.Assert;
  4. namespace Zenject.Tests.Bindings
  5. {
  6. [TestFixture]
  7. public class TestFromMethod : ZenjectUnitTestFixture
  8. {
  9. [Test]
  10. public void TestSingle()
  11. {
  12. var foo = new Foo();
  13. Container.Bind<Foo>().FromMethod(ctx => foo).AsSingle().NonLazy();
  14. Assert.IsEqual(Container.Resolve<Foo>(), foo);
  15. }
  16. [Test]
  17. public void TestTransient()
  18. {
  19. var foo = new Foo();
  20. Container.Bind<Foo>().FromMethod(ctx => foo).AsTransient().NonLazy();
  21. Assert.IsEqual(Container.Resolve<Foo>(), foo);
  22. }
  23. [Test]
  24. public void TestCached()
  25. {
  26. var foo = new Foo();
  27. Container.Bind<Foo>().FromMethod(ctx => foo).AsSingle().NonLazy();
  28. Assert.IsEqual(Container.Resolve<Foo>(), foo);
  29. }
  30. Foo CreateFoo(InjectContext ctx)
  31. {
  32. return new Foo();
  33. }
  34. [Test]
  35. public void TestTransient2()
  36. {
  37. int numCalls = 0;
  38. Func<InjectContext, Foo> method = ctx =>
  39. {
  40. numCalls++;
  41. return null;
  42. };
  43. Container.Bind<Foo>().FromMethod(method).AsTransient().NonLazy();
  44. Container.Bind<IFoo>().To<Foo>().FromMethod(method).AsTransient().NonLazy();
  45. Container.Resolve<Foo>();
  46. Container.Resolve<Foo>();
  47. Container.Resolve<Foo>();
  48. Container.Resolve<IFoo>();
  49. Assert.IsEqual(numCalls, 4);
  50. }
  51. [Test]
  52. public void TestCached2()
  53. {
  54. Container.Bind(typeof(Foo), typeof(IFoo)).To<Foo>().FromMethod(ctx => new Foo()).AsSingle().NonLazy();
  55. Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
  56. Assert.IsEqual(Container.Resolve<Foo>(), Container.Resolve<IFoo>());
  57. }
  58. interface IFoo
  59. {
  60. }
  61. class Foo : IFoo
  62. {
  63. }
  64. }
  65. }