public void DoNotGenerateScopeIfNoServicesWithLifetimeScopedAreDefined() { // Given var input = CompilationBuilder.CreateAssemblyWithCode( @"namespace Demo.Domain { public interface IFoo { } }", @"namespace Demo.Domain { using CustomCode.CompileTimeInject.Annotations; [Export] public sealed class Foo : IFoo { } }"); var sourceGenerator = new ScopeGenerator(); var testEnvironment = CSharpGeneratorDriver.Create(sourceGenerator); // When testEnvironment.RunGeneratorsAndUpdateCompilation( compilation: input, outputCompilation: out var output, diagnostics: out var diagnostics); // Then Assert.False(diagnostics.HasErrors()); Assert.False(output.ContainsClass("Scope")); }
public void GenerateScopeDisposeMethod() { // Given var input = CompilationBuilder.CreateAssemblyWithCode( @"namespace Demo.Domain { public interface IFoo { } }", @"namespace Demo.Domain { using CustomCode.CompileTimeInject.Annotations; [Export(Lifetime.Scoped)] public sealed class Foo : IFoo { } }"); var sourceGenerator = new ScopeGenerator(); var testEnvironment = CSharpGeneratorDriver.Create(sourceGenerator); // When testEnvironment.RunGeneratorsAndUpdateCompilation( compilation: input, outputCompilation: out var output, diagnostics: out var diagnostics); // Then Assert.False(diagnostics.HasErrors()); Assert.True(output.ContainsTypeWithMethodImplementation( "Scope", @"public void Dispose() { DisposeAction(); }")); }
public void GenerateScopeGetServicesMethod() { // Given var input = CompilationBuilder.CreateAssemblyWithCode( @"namespace Demo.Domain { public interface IFoo { } }", @"namespace Demo.Domain { using CustomCode.CompileTimeInject.Annotations; [Export(Lifetime.Scoped)] public sealed class Foo : IFoo { } }"); var sourceGenerator = new ScopeGenerator(); var testEnvironment = CSharpGeneratorDriver.Create(sourceGenerator); // When testEnvironment.RunGeneratorsAndUpdateCompilation( compilation: input, outputCompilation: out var output, diagnostics: out var diagnostics); // Then Assert.False(diagnostics.HasErrors()); Assert.True(output.ContainsTypeWithMethodImplementation( "Scope", @"public IEnumerable<T> GetServices<T>() where T : class { if (Factory is IServiceFactory<IEnumerable<T>> collectionFactory) { return collectionFactory.CreateOrGetService(); } if (Factory is IServiceFactory<T> factory) { return new List<T> { factory.CreateOrGetService() }; } return Enumerable.Empty<T>(); }")); }