// Author: simon.gockner // Created: 2024-11-25 // Copyright(c) 2024 SimonG. All Rights Reserved. using LightweightIocContainer; using NUnit.Framework; namespace Test.LightweightIocContainer; [TestFixture] public class AsyncFactoryTest { public interface ITest { bool IsInitialized { get; } Task Initialize(); } public class Test : ITest { public bool IsInitialized { get; private set; } public virtual async Task Initialize() { await Task.Delay(200); IsInitialized = true; } } public class MultitonTest(int id) : Test { public int Id { get; } = id; public override async Task Initialize() { if (IsInitialized) throw new Exception(); await base.Initialize(); } } public interface ITestFactory { Task Create(); } public interface IMultitonTestFactory { Task Create(int id); } [Test] public async Task TestAsyncFactoryResolve() { IocContainer container = new(); container.Register(r => r.Add().WithFactory()); ITestFactory testFactory = container.Resolve(); ITest test = await testFactory.Create(); Assert.IsInstanceOf(test); } [Test] public async Task TestAsyncFactoryResolveOnCreateCalled() { IocContainer container = new(); container.Register(r => r.Add().OnCreateAsync(t => t.Initialize()).WithFactory()); ITestFactory testFactory = container.Resolve(); ITest test = await testFactory.Create(); Assert.IsInstanceOf(test); Assert.That(test.IsInitialized, Is.True); } [Test] public async Task TestAsyncMultitonFactoryResolveOnCreateCalledCorrectly() { IocContainer container = new(); container.Register(r => r.AddMultiton().OnCreateAsync(t => t.Initialize()).WithFactory()); IMultitonTestFactory testFactory = container.Resolve(); ITest test1 = await testFactory.Create(1); ITest test2 = await testFactory.Create(2); ITest anotherTest1 = await testFactory.Create(1); Assert.IsInstanceOf(test1); Assert.That(test1.IsInitialized, Is.True); Assert.IsInstanceOf(test2); Assert.That(test2.IsInitialized, Is.True); Assert.AreSame(test1, anotherTest1); } }