├── .idea └── .idea.TomLonghurst.AllOf │ └── .idea │ ├── .name │ ├── encodings.xml │ ├── vcs.xml │ ├── indexLayout.xml │ └── .gitignore ├── TomLonghurst.AllOf.UnitTests ├── Usings.cs ├── TestModels │ ├── Classes │ │ ├── MyScopedTestClass.cs │ │ ├── MySingletonTestClass.cs │ │ ├── MyTransientTestClass.cs │ │ ├── MyClassWithoutAttribute.cs │ │ ├── MyTestClass.cs │ │ ├── MyTestClass2.cs │ │ ├── MyTestClass3.cs │ │ ├── MyAsyncTestClass.cs │ │ ├── MyBaseTestClass.cs │ │ ├── MyAsyncTestClass2.cs │ │ ├── MyAsyncTestClass3.cs │ │ ├── MyValueTaskAsyncTestClass.cs │ │ ├── MyValueTaskAsyncTestClass2.cs │ │ └── MyValueTaskAsyncTestClass3.cs │ └── Interfaces │ │ ├── IMyDummyTestInterface.cs │ │ ├── IMyInterfaceWithoutAttribute.cs │ │ ├── IMyTestInterface.cs │ │ ├── IMyAsyncTestInterface.cs │ │ └── IMyValueTaskAsyncTestInterface.cs ├── PublisherOf.cs ├── PublisherOfImpl.cs ├── ConstructorWithAllOfWrapper.cs ├── ConstructorUsingInterfaceWithoutAttribute.cs ├── TomLonghurst.AllOf.UnitTests.csproj ├── DummyClassTests.cs └── Tests.cs ├── TomLonghurst.AllOf ├── Models │ ├── IAllOf.cs │ ├── AllOf.cs │ ├── AllOfData.cs │ └── AllOfImpl_Base.cs ├── SourceGenerator │ ├── Attributes │ │ ├── GenerateAllOfAttribute.cs │ │ └── AllOfWrapperAttribute.cs │ ├── IndentifiedAllOf.cs │ ├── Helpers │ │ ├── SymbolDisplayFormats.cs │ │ ├── CodeGenerationTextWriter.cs │ │ └── NamespaceHelper.cs │ ├── AllOfSyntaxReceiver.cs │ └── AllOfGenerator.cs ├── Extensions │ ├── EnumerableExtensions.cs │ ├── TypeExtensions.cs │ └── DependencyInjectionExtensions.cs └── TomLonghurst.AllOf.csproj ├── TomLonghurst.AllOf.UnitTests.WrappedAllOf ├── IInterfaceToWrap.cs ├── PublisherOf.cs ├── Impl1.cs ├── Impl2.cs ├── Impl3.cs ├── PublisherOfImpl.cs ├── TomLonghurst.AllOf.UnitTests.WrappedAllOf.csproj └── Tests.cs ├── TomLonghurst.AllOf.UnitTests.DependentProject ├── MyDependentClass.cs ├── IMyDependentInterface.cs ├── TomLonghurst.AllOf.UnitTests.DependentProject.csproj └── IMyInterfaceInWrapper.cs ├── TomLonghurst.AllOf.sln ├── README.md ├── .gitignore └── LICENSE /.idea/.idea.TomLonghurst.AllOf/.idea/.name: -------------------------------------------------------------------------------- 1 | TomLonghurst.AllOf -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using NUnit.Framework; -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Models/IAllOf.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.Models; 2 | 3 | public interface IAllOf 4 | { 5 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/IInterfaceToWrap.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 2 | 3 | public interface IInterfaceToWrap 4 | { 5 | void Blah(); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/PublisherOf.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 2 | 3 | public interface PublisherOf 4 | { 5 | T ForEachSubscriber(); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyScopedTestClass.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 2 | 3 | public class MyScopedTestClass : MyBaseTestClass 4 | { 5 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MySingletonTestClass.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 2 | 3 | public class MySingletonTestClass : MyBaseTestClass 4 | { 5 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyTransientTestClass.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 2 | 3 | public class MyTransientTestClass : MyBaseTestClass 4 | { 5 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Interfaces/IMyDummyTestInterface.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | public interface IMyDummyTestInterface 4 | { 5 | void Blah(); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/PublisherOf.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests; 2 | 3 | // ReSharper disable once InconsistentNaming 4 | public interface PublisherOf 5 | { 6 | T ForEachSubscriber(); 7 | } -------------------------------------------------------------------------------- /.idea/.idea.TomLonghurst.AllOf/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Interfaces/IMyInterfaceWithoutAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | public interface IMyInterfaceWithoutAttribute 4 | { 5 | void DoSomething(); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Interfaces/IMyTestInterface.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | public interface IMyTestInterface 4 | { 5 | public void Blah(Action action); 6 | } -------------------------------------------------------------------------------- /.idea/.idea.TomLonghurst.AllOf/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Models/AllOf.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.Models; 2 | 3 | // ReSharper disable once InconsistentNaming 4 | public interface AllOf : IAllOf 5 | { 6 | IEnumerable Items { get; } 7 | public T OnEach(); 8 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/Attributes/GenerateAllOfAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.SourceGenerator.Attributes; 2 | 3 | [AttributeUsage(AttributeTargets.Interface)] 4 | public class GenerateAllOfAttribute : Attribute 5 | { 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/Impl1.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 2 | 3 | public class Impl1 : IInterfaceToWrap 4 | { 5 | public void Blah() 6 | { 7 | Console.WriteLine(GetType().Name); 8 | } 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/Impl2.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 2 | 3 | public class Impl2 : IInterfaceToWrap 4 | { 5 | public void Blah() 6 | { 7 | Console.WriteLine(GetType().Name); 8 | } 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/Impl3.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 2 | 3 | public class Impl3 : IInterfaceToWrap 4 | { 5 | public void Blah() 6 | { 7 | Console.WriteLine(GetType().Name); 8 | } 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Interfaces/IMyAsyncTestInterface.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | public interface IMyAsyncTestInterface 4 | { 5 | public Task BlahAsync(Func action); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Models/AllOfData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | 3 | namespace TomLonghurst.AllOf.Models; 4 | 5 | public static class AllOfData 6 | { 7 | public static readonly ConcurrentDictionary Implementations = new(); 8 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/Attributes/AllOfWrapperAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.SourceGenerator.Attributes; 2 | 3 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] 4 | public class AllOfWrapperAttribute : Attribute 5 | { 6 | } -------------------------------------------------------------------------------- /.idea/.idea.TomLonghurst.AllOf/.idea/indexLayout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Interfaces/IMyValueTaskAsyncTestInterface.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | public interface IMyValueTaskAsyncTestInterface 4 | { 5 | public ValueTask BlahAsync(Func action); 6 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.DependentProject/MyDependentClass.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.UnitTests.DependentProject; 2 | 3 | public class MyDependentClass : IMyDependentInterface 4 | { 5 | public void MyDependentMethod(ref int result) 6 | { 7 | result = 123; 8 | } 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.DependentProject/IMyDependentInterface.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.SourceGenerator.Attributes; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.DependentProject; 4 | 5 | [GenerateAllOf] 6 | public interface IMyDependentInterface 7 | { 8 | void MyDependentMethod(ref int result); 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/IndentifiedAllOf.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace TomLonghurst.AllOf.SourceGenerator; 4 | 5 | public class IndentifiedAllOf 6 | { 7 | public INamedTypeSymbol? InterfaceType { get; set; } 8 | 9 | public IReadOnlyList? MethodsInInterface { get; set; } 10 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyClassWithoutAttribute.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyClassWithoutAttribute : IMyInterfaceWithoutAttribute 6 | { 7 | public void DoSomething() 8 | { 9 | } 10 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Extensions/EnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.Extensions; 2 | 3 | internal static class EnumerableExtensions 4 | { 5 | public static IEnumerable DistinctBy(this IEnumerable items, Func property) 6 | { 7 | return items.GroupBy(property).Select(x => x.First()); 8 | } 9 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyTestClass.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyTestClass : IMyTestInterface 6 | { 7 | public void Blah(Action action) 8 | { 9 | action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyTestClass2.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyTestClass2 : IMyTestInterface 6 | { 7 | public void Blah(Action action) 8 | { 9 | action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyTestClass3.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyTestClass3 : IMyTestInterface 6 | { 7 | public void Blah(Action action) 8 | { 9 | action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /.idea/.idea.TomLonghurst.AllOf/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Rider ignored files 5 | /modules.xml 6 | /projectSettingsUpdater.xml 7 | /contentModel.xml 8 | /.idea.TomLonghurst.AllOf.iml 9 | # Editor-based HTTP Client requests 10 | /httpRequests/ 11 | # Datasource local storage ignored files 12 | /dataSources/ 13 | /dataSources.local.xml 14 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyAsyncTestClass.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyAsyncTestClass : IMyAsyncTestInterface 6 | { 7 | public async Task BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyBaseTestClass.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyBaseTestClass : IMyDummyTestInterface 6 | { 7 | public int BlahCount { get; private set; } 8 | public void Blah() 9 | { 10 | BlahCount++; 11 | } 12 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyAsyncTestClass2.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyAsyncTestClass2 : IMyAsyncTestInterface 6 | { 7 | public async Task BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyAsyncTestClass3.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyAsyncTestClass3 : IMyAsyncTestInterface 6 | { 7 | public async Task BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyValueTaskAsyncTestClass.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyValueTaskAsyncTestClass : IMyValueTaskAsyncTestInterface 6 | { 7 | public async ValueTask BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyValueTaskAsyncTestClass2.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyValueTaskAsyncTestClass2 : IMyValueTaskAsyncTestInterface 6 | { 7 | public async ValueTask BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TestModels/Classes/MyValueTaskAsyncTestClass3.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | 5 | public class MyValueTaskAsyncTestClass3 : IMyValueTaskAsyncTestInterface 6 | { 7 | public async ValueTask BlahAsync(Func action) 8 | { 9 | await action(GetType().Name); 10 | } 11 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/PublisherOfImpl.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.Models; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests; 4 | 5 | public class PublisherOfImpl : PublisherOf 6 | { 7 | private readonly AllOf _allOf; 8 | 9 | public PublisherOfImpl(AllOf allOf) 10 | { 11 | _allOf = allOf; 12 | } 13 | 14 | public T ForEachSubscriber() 15 | { 16 | return _allOf.OnEach(); 17 | } 18 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/PublisherOfImpl.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.Models; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 4 | 5 | public class PublisherOfImpl : PublisherOf 6 | { 7 | private readonly AllOf _allOf; 8 | 9 | public PublisherOfImpl(AllOf allOf) 10 | { 11 | _allOf = allOf; 12 | } 13 | 14 | public T ForEachSubscriber() 15 | { 16 | return _allOf.OnEach(); 17 | } 18 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Extensions/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.Extensions; 2 | 3 | public static class TypeExtensions 4 | { 5 | public static string GetFullNameWithoutGenericArity(this Type type) 6 | { 7 | var name = type.FullName; 8 | 9 | if (name == null) 10 | { 11 | return string.Empty; 12 | } 13 | 14 | var index = name.IndexOf('`'); 15 | return index == -1 ? name : name.Substring(0, index); 16 | } 17 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/ConstructorWithAllOfWrapper.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests; 4 | 5 | public class ConstructorWithAllOfWrapper 6 | { 7 | public PublisherOf Publisher { get; } 8 | 9 | public ConstructorWithAllOfWrapper(PublisherOf publisher) 10 | { 11 | Publisher = publisher; 12 | } 13 | 14 | public void DoSomething() 15 | { 16 | } 17 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.DependentProject/TomLonghurst.AllOf.UnitTests.DependentProject.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/ConstructorUsingInterfaceWithoutAttribute.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.Models; 2 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 3 | 4 | namespace TomLonghurst.AllOf.UnitTests; 5 | 6 | public class ConstructorUsingInterfaceWithoutAttribute 7 | { 8 | public AllOf MyTestInterface { get; } 9 | 10 | public ConstructorUsingInterfaceWithoutAttribute(AllOf myTestInterface) 11 | { 12 | MyTestInterface = myTestInterface; 13 | } 14 | 15 | public void DoSomething() 16 | { 17 | } 18 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Extensions/DependencyInjectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TomLonghurst.AllOf.Models; 4 | 5 | namespace TomLonghurst.AllOf.Extensions; 6 | 7 | public static class DependencyInjectionExtensions 8 | { 9 | public static IServiceCollection AddAllOfs(this IServiceCollection services) 10 | { 11 | if (services.IsReadOnly) 12 | { 13 | throw new ReadOnlyException($"{nameof(services)} is read only"); 14 | } 15 | 16 | return services.AddTransient(typeof(AllOf<>), typeof(AllOfImpl<>)); 17 | } 18 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/Models/AllOfImpl_Base.cs: -------------------------------------------------------------------------------- 1 | namespace TomLonghurst.AllOf.Models; 2 | 3 | internal class AllOfImpl : AllOf 4 | { 5 | private T GetRegisteredImplementation() 6 | { 7 | if (AllOfData.Implementations.TryGetValue(typeof(T), out var implementationType)) 8 | { 9 | return (T) Activator.CreateInstance(implementationType, Items); 10 | } 11 | 12 | throw new ArgumentNullException(typeof(T).Name); 13 | } 14 | 15 | public IEnumerable Items { get; } 16 | 17 | public AllOfImpl(IEnumerable items) 18 | { 19 | Items = items; 20 | } 21 | 22 | public T OnEach() 23 | { 24 | return GetRegisteredImplementation(); 25 | } 26 | 27 | public static implicit operator T(AllOfImpl allOf) => allOf.OnEach(); 28 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/Helpers/SymbolDisplayFormats.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace TomLonghurst.AllOf.SourceGenerator.Helpers; 4 | 5 | public static class SymbolDisplayFormats 6 | { 7 | public static readonly SymbolDisplayFormat NamespaceAndType = 8 | new( 9 | SymbolDisplayGlobalNamespaceStyle.Omitted, 10 | SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, 11 | SymbolDisplayGenericsOptions.IncludeTypeParameters 12 | ); 13 | 14 | public static readonly SymbolDisplayFormat GenericBase = 15 | new( 16 | SymbolDisplayGlobalNamespaceStyle.Omitted, 17 | SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, 18 | SymbolDisplayGenericsOptions.None 19 | ); 20 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/TomLonghurst.AllOf.UnitTests.WrappedAllOf.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | net6.0 12 | enable 13 | enable 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.WrappedAllOf/Tests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using NUnit.Framework; 3 | using TomLonghurst.AllOf.Extensions; 4 | 5 | namespace TomLonghurst.AllOf.UnitTests.WrappedAllOf; 6 | 7 | public class Tests 8 | { 9 | [Test] 10 | public void Test1() 11 | { 12 | var serviceProvider = new ServiceCollection() 13 | .AddSingleton() 14 | .AddSingleton() 15 | .AddSingleton() 16 | .AddTransient(typeof(PublisherOf<>), typeof(PublisherOfImpl<>)) 17 | .AddAllOfs() 18 | .BuildServiceProvider(); 19 | 20 | var myInterface = serviceProvider.GetRequiredService>(); 21 | 22 | Assert.That(myInterface.GetType().Name, Is.EqualTo("PublisherOfImpl`1")); 23 | Assert.That(myInterface.ForEachSubscriber(), Is.Not.Null); 24 | } 25 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests.DependentProject/IMyInterfaceInWrapper.cs: -------------------------------------------------------------------------------- 1 | using TomLonghurst.AllOf.Models; 2 | 3 | namespace TomLonghurst.AllOf.UnitTests.DependentProject; 4 | 5 | public interface IMyInterfaceInWrapper 6 | { 7 | void DoSomething(); 8 | } 9 | 10 | public class MyClassInWrapper : IMyInterfaceInWrapper 11 | { 12 | public void DoSomething() 13 | { 14 | 15 | } 16 | } 17 | 18 | public interface MyWrapper 19 | { 20 | T Get(); 21 | } 22 | 23 | public class MyWrapperImpl : MyWrapper 24 | { 25 | private readonly AllOf _allOf; 26 | 27 | public MyWrapperImpl(AllOf allOf) 28 | { 29 | _allOf = allOf; 30 | } 31 | 32 | public T Get() 33 | { 34 | return _allOf.OnEach(); 35 | } 36 | } 37 | 38 | public class MyConstructor 39 | { 40 | private readonly MyWrapper _blah; 41 | 42 | public MyConstructor(MyWrapper blah) 43 | { 44 | _blah = blah; 45 | } 46 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/Helpers/CodeGenerationTextWriter.cs: -------------------------------------------------------------------------------- 1 | using System.CodeDom.Compiler; 2 | 3 | namespace TomLonghurst.AllOf.SourceGenerator.Helpers; 4 | 5 | public class CodeGenerationTextWriter : IndentedTextWriter 6 | { 7 | public CodeGenerationTextWriter() : base(new StringWriter()) 8 | { 9 | } 10 | 11 | public override void Write(char value) 12 | { 13 | if (value is '{') 14 | { 15 | Indent++; 16 | } 17 | 18 | if (value is '}') 19 | { 20 | Indent--; 21 | } 22 | } 23 | 24 | public override void WriteLine(string s) 25 | { 26 | var trimmed = s.Trim(); 27 | 28 | if (trimmed.StartsWith("}")) 29 | { 30 | Indent--; 31 | } 32 | 33 | base.WriteLine(s); 34 | 35 | if (trimmed.StartsWith("{")) 36 | { 37 | Indent++; 38 | } 39 | } 40 | 41 | public override string ToString() 42 | { 43 | Flush(); 44 | return InnerWriter.ToString(); 45 | } 46 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/Helpers/NamespaceHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace TomLonghurst.AllOf.SourceGenerator.Helpers; 4 | 5 | public static class NamespaceHelper 6 | { 7 | public static string GetUsingStatementsForTypes(this GeneratorExecutionContext context, params Type[] types) 8 | { 9 | return GetUsingStatementsForTypes(context, Array.Empty(), types); 10 | } 11 | 12 | public static string GetUsingStatementsForTypes(this GeneratorExecutionContext context, IEnumerable typeSymbols, params Type[] types) 13 | { 14 | var namespaces = types 15 | .Select(type => context.Compilation.GetTypeByMetadataName(type.FullName).ContainingNamespace.ToString()) 16 | .Concat(typeSymbols.Select(type => type.ContainingNamespace.ToString())) 17 | .Distinct(); 18 | 19 | return WriteUsingStatements(namespaces); 20 | } 21 | 22 | private static string WriteUsingStatements(IEnumerable namespaces) 23 | { 24 | return string.Join(Environment.NewLine, namespaces.Select(@namespace => $"using {@namespace};")); 25 | } 26 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/TomLonghurst.AllOf.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf/TomLonghurst.AllOf.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | enable 6 | enable 7 | latest 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | true 25 | 1.4.1 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TomLonghurst.AllOf", "TomLonghurst.AllOf\TomLonghurst.AllOf.csproj", "{D8AEB1B9-0C42-4193-869E-47B1D0E377F8}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TomLonghurst.AllOf.UnitTests", "TomLonghurst.AllOf.UnitTests\TomLonghurst.AllOf.UnitTests.csproj", "{001BD00C-3766-4949-A088-4F58B85A253D}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TomLonghurst.AllOf.UnitTests.DependentProject", "TomLonghurst.AllOf.UnitTests.DependentProject\TomLonghurst.AllOf.UnitTests.DependentProject.csproj", "{56D50A11-2440-44DD-8518-CDD223C1B52E}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TomLonghurst.AllOf.UnitTests.WrappedAllOf", "TomLonghurst.AllOf.UnitTests.WrappedAllOf\TomLonghurst.AllOf.UnitTests.WrappedAllOf.csproj", "{68C91285-0D69-4508-9C69-AEB024315DDF}" 10 | EndProject 11 | Global 12 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 13 | Debug|Any CPU = Debug|Any CPU 14 | Release|Any CPU = Release|Any CPU 15 | EndGlobalSection 16 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 17 | {D8AEB1B9-0C42-4193-869E-47B1D0E377F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {D8AEB1B9-0C42-4193-869E-47B1D0E377F8}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {D8AEB1B9-0C42-4193-869E-47B1D0E377F8}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {D8AEB1B9-0C42-4193-869E-47B1D0E377F8}.Release|Any CPU.Build.0 = Release|Any CPU 21 | {001BD00C-3766-4949-A088-4F58B85A253D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {001BD00C-3766-4949-A088-4F58B85A253D}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {001BD00C-3766-4949-A088-4F58B85A253D}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {001BD00C-3766-4949-A088-4F58B85A253D}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {56D50A11-2440-44DD-8518-CDD223C1B52E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {56D50A11-2440-44DD-8518-CDD223C1B52E}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {56D50A11-2440-44DD-8518-CDD223C1B52E}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {56D50A11-2440-44DD-8518-CDD223C1B52E}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {68C91285-0D69-4508-9C69-AEB024315DDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {68C91285-0D69-4508-9C69-AEB024315DDF}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {68C91285-0D69-4508-9C69-AEB024315DDF}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {68C91285-0D69-4508-9C69-AEB024315DDF}.Release|Any CPU.Build.0 = Release|Any CPU 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/DummyClassTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using TomLonghurst.AllOf.Extensions; 3 | using TomLonghurst.AllOf.UnitTests.TestModels.Classes; 4 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 5 | 6 | namespace TomLonghurst.AllOf.UnitTests; 7 | 8 | public class DummyClassTests 9 | { 10 | [Test] 11 | public void DummyClass() 12 | { 13 | var services = new ServiceCollection() 14 | .AddTransient() 15 | .AddScoped() 16 | .AddSingleton() 17 | .AddAllOfs() 18 | .BuildServiceProvider(); 19 | 20 | var scope = services.CreateScope().ServiceProvider; 21 | scope.GetRequiredService>().OnEach().Blah(); 22 | 23 | var transient = Get(scope); 24 | var scoped = Get(scope); 25 | var singleton = Get(scope); 26 | 27 | Assert.That(transient.BlahCount, Is.EqualTo(0)); 28 | Assert.That(scoped.BlahCount, Is.EqualTo(1)); 29 | Assert.That(singleton.BlahCount, Is.EqualTo(1)); 30 | 31 | scope.GetRequiredService>().OnEach().Blah(); 32 | 33 | Assert.That(transient.BlahCount, Is.EqualTo(0)); 34 | Assert.That(scoped.BlahCount, Is.EqualTo(2)); 35 | Assert.That(singleton.BlahCount, Is.EqualTo(2)); 36 | 37 | var newScope = services.CreateScope().ServiceProvider; 38 | 39 | var newScopedTransient = Get(newScope); 40 | var newScopedScoped = Get(newScope); 41 | var newScopedSingleton = Get(newScope); 42 | 43 | Assert.That(newScopedTransient.BlahCount, Is.EqualTo(0)); 44 | Assert.That(newScopedScoped.BlahCount, Is.EqualTo(0)); 45 | Assert.That(newScopedSingleton.BlahCount, Is.EqualTo(2)); 46 | 47 | newScope.GetRequiredService>().OnEach().Blah(); 48 | 49 | Assert.That(newScopedTransient.BlahCount, Is.EqualTo(0)); 50 | Assert.That(newScopedScoped.BlahCount, Is.EqualTo(1)); 51 | Assert.That(newScopedSingleton.BlahCount, Is.EqualTo(3)); 52 | 53 | T Get(IServiceProvider? scope = null) where T : class 54 | { 55 | return scope.GetService>() 56 | .Items 57 | .OfType() 58 | .First(); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/AllOfSyntaxReceiver.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp.Syntax; 4 | using TomLonghurst.AllOf.Extensions; 5 | using TomLonghurst.AllOf.Models; 6 | using TomLonghurst.AllOf.SourceGenerator.Helpers; 7 | 8 | namespace TomLonghurst.AllOf.SourceGenerator; 9 | 10 | internal class AllOfSyntaxReceiver : ISyntaxContextReceiver 11 | { 12 | public AllOfSyntaxReceiver() 13 | { 14 | #if DEBUG 15 | if (!System.Diagnostics.Debugger.IsAttached) 16 | { 17 | //System.Diagnostics.Debugger.Launch(); 18 | } 19 | #endif 20 | } 21 | 22 | public List Identified { get; } = new(); 23 | 24 | public void OnVisitSyntaxNode(GeneratorSyntaxContext context) 25 | { 26 | if (context.Node is TypeSyntax typeSyntax) 27 | { 28 | Process(context, typeSyntax); 29 | } 30 | } 31 | 32 | private void Process(GeneratorSyntaxContext context, TypeSyntax typeSyntax) 33 | { 34 | var symbol = GetSymbol(context, typeSyntax); 35 | 36 | if (symbol is not INamedTypeSymbol typeSymbol) 37 | { 38 | return; 39 | } 40 | 41 | var interfaceArguments = typeSymbol.TypeArguments 42 | .OfType() 43 | .Where(nts => nts.TypeKind == TypeKind.Interface) 44 | .Where(HasNoReturnTypes); 45 | 46 | foreach (var interfaceArgument in interfaceArguments) 47 | { 48 | var methods = GetMethods(interfaceArgument); 49 | 50 | Identified.Add(new IndentifiedAllOf 51 | { 52 | InterfaceType = interfaceArgument, 53 | MethodsInInterface = methods 54 | }); 55 | } 56 | 57 | if (symbol.ToDisplayString(SymbolDisplayFormats.GenericBase) == 58 | typeof(AllOf<>).GetFullNameWithoutGenericArity()) 59 | { 60 | 61 | } 62 | 63 | 64 | } 65 | 66 | private bool HasNoReturnTypes(INamedTypeSymbol type) 67 | { 68 | var members = GetMembers(type); 69 | 70 | if (members.OfType().Any()) 71 | { 72 | return false; 73 | } 74 | 75 | return members.OfType().All(m => 76 | { 77 | if (m.ReturnsVoid) 78 | { 79 | return true; 80 | } 81 | 82 | var fullTypeName = m.ReturnType.ToDisplayString(SymbolDisplayFormats.NamespaceAndType); 83 | return fullTypeName == typeof(Task).FullName || fullTypeName == typeof(ValueTask).FullName; 84 | }); 85 | } 86 | 87 | private static ImmutableArray GetMembers(INamedTypeSymbol type) 88 | { 89 | return type.GetMembers().Concat( 90 | type.AllInterfaces.SelectMany(i => i.GetMembers()) 91 | ) 92 | .ToImmutableArray(); 93 | } 94 | 95 | private ISymbol? GetSymbol(GeneratorSyntaxContext context, SyntaxNode syntaxNode) 96 | { 97 | return context.SemanticModel.GetDeclaredSymbol(syntaxNode) ?? context.SemanticModel.GetSymbolInfo(syntaxNode).Symbol; 98 | } 99 | 100 | private static List GetMethods(ITypeSymbol interfaceSymbol) 101 | { 102 | var interfaceMembers = interfaceSymbol.GetMembers(); 103 | 104 | var methods = interfaceMembers 105 | .OfType() 106 | .ToList(); 107 | 108 | var allowedTypes = new[] 109 | { 110 | typeof(Task).FullName, 111 | typeof(void).FullName, 112 | typeof(ValueTask).FullName 113 | }; 114 | 115 | var returnTypeExceptions = methods 116 | .Where(m => !allowedTypes.Contains(m.ReturnType.ToDisplayString(SymbolDisplayFormats.NamespaceAndType))) 117 | .Select(m => 118 | new ArgumentException( 119 | $"Only void or Task return types are supported. Cannot convert IEnumerable<{m.ReturnType}> to {m.ReturnType}") 120 | ).ToList(); 121 | 122 | if (returnTypeExceptions.Any()) 123 | { 124 | throw new AggregateException(returnTypeExceptions); 125 | } 126 | 127 | return methods; 128 | } 129 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AllOf 2 | 3 | Use `Producer/Consumer` type classes without creating Producer classes just to call Consumer classes. 4 | 5 | - Create your implementations 6 | - Register them under the same interface 7 | - Inject in AllOf and use that to send a 'Publish' command. 8 | 9 | ## Support 10 | 11 | If you like this library, consider buying me a coffee. 12 | 13 | Buy Me A Coffee 14 | 15 | ## Example 16 | Reduce: 17 | 18 | ```csharp 19 | public class MyImplementation1 : IMyInterface { ... } 20 | public class MyImplementation2 : IMyInterface { ... } 21 | public class MyImplementation3 : IMyInterface { ... } 22 | 23 | public interface IMyPublisher 24 | { 25 | void PublishSomething(); 26 | Task PublishSomethingAsync(); 27 | } 28 | 29 | public class MyPublisher : IMyPublisher 30 | { 31 | private readonly IEnumerable _myInterfaces; 32 | 33 | public MyPublisher(IEnumerable myInterfaces) 34 | { 35 | _myInterfaces = myInterfaces; 36 | } 37 | 38 | public void PublishSomething() 39 | { 40 | foreach(var myInterface in _myInterfaces) 41 | { 42 | myInterface.DoSomething(); 43 | } 44 | } 45 | 46 | public async Task PublishSomethingAsync() 47 | { 48 | var tasks = _myInterfaces.Select(myInterface => myInterface.DoSomethingAsync()); 49 | await Task.WhenAll(tasks); 50 | } 51 | } 52 | 53 | public class MyWorker 54 | { 55 | private readonly IMyPublisher _myPublisher; 56 | 57 | public MyWorker(IMyPublisher _myPublisher) 58 | { 59 | _myPublisher = myPublisher; 60 | } 61 | 62 | public async Task DoSomething() 63 | { 64 | ... 65 | _myPublisher.PublishSomething(); 66 | await _myPublisher.PublishSomethingAsync(); 67 | } 68 | } 69 | ``` 70 | 71 | To 72 | 73 | ```csharp 74 | public class MyImplementation1 : IMyInterface { ... } 75 | public class MyImplementation2 : IMyInterface { ... } 76 | public class MyImplementation3 : IMyInterface { ... } 77 | 78 | public class MyWorker 79 | { 80 | private readonly AllOf _myInterfaces; 81 | 82 | public MyWorker(AllOf myInterfaces) 83 | { 84 | _myInterfaces = myInterfaces; 85 | } 86 | 87 | public async Task DoSomething() 88 | { 89 | ... 90 | _myInterfaces.OnEach().DoSomething(); 91 | await _myInterfaces.OnEach().DoSomethingAsync(); 92 | } 93 | } 94 | ``` 95 | 96 | It may not seem like much, but it eliminates an entire class. 97 | It also means you don't need to handle the looping and Task (if async) management on these methods. 98 | 99 | ## Usage 100 | 101 | 1. Register multiple implementations of your interfaces(s) in your ServiceCollection 102 | 103 | ```csharp 104 | services.AddSingleton() 105 | .AddScoped() 106 | .AddTransient(); 107 | ``` 108 | 109 | 2. Call `AddAllOfs()` on your ServiceCollection 110 | 111 | ```csharp 112 | services.AddAllOfs() 113 | ``` 114 | 115 | 3. Inject `AllOf` into your class 116 | 117 | ```csharp 118 | public class MyWorker 119 | { 120 | private readonly AllOf _myInterfaces; 121 | 122 | public MyWorker(AllOf myInterfaces) 123 | { 124 | _myInterfaces = myInterfaces; 125 | } 126 | } 127 | ``` 128 | 129 | 4. Call `AllOf.OnEach().SomeMethod()` and it'll call the same method in all of the different implementations. This handles asynchronous Tasks as well as synchronous methods, so no loop or Task handling for you to implement. 130 | 131 | ```csharp 132 | _myInterfaces.OnEach().DoSomething(); 133 | await _myInterface.OnEach().DoSomethingElseAsync(); 134 | ``` 135 | 136 | The above will essentially do: 137 | 138 | ```csharp 139 | MyImplementation1.DoSomething(); 140 | MyImplementation2.DoSomething(); 141 | MyImplementation3.DoSomething(); 142 | 143 | await Task.WhenAll( 144 | MyImplementation1.DoSomethingElseAsync(), 145 | MyImplementation2.DoSomethingElseAsync(), 146 | MyImplementation3.DoSomethingElseAsync() 147 | ); 148 | ``` 149 | 150 | # AllOf<> 151 | 152 | `AllOf<>` is an interface so can be easily mocked. As well as `OnEach()`, it holds an `Items` property which is an `IEnumerable` if you need to access your enumerable of implementations. 153 | 154 | ## Custom Naming 155 | 156 | If you want to change the naming, create a wrapper class around it and register it in the DI. 157 | E.g. 158 | 159 | ```csharp 160 | public interface PublisherOf 161 | { 162 | T ForEachSubscriber(); 163 | } 164 | 165 | public class PublisherOfImpl : PublisherOf 166 | { 167 | private readonly AllOf _allOf; 168 | 169 | public PublisherOfImpl(AllOf allOf) 170 | { 171 | _allOf = allOf; 172 | } 173 | 174 | public T ForEachSubscriber() 175 | { 176 | return _allOf.OnEach(); 177 | } 178 | } 179 | ``` 180 | 181 | in Startup do 182 | ```csharp 183 | services.AddTransient(typeof(PublisherOf<>), typeof(PublisherOfImpl<>)) 184 | ``` 185 | 186 | And then you can inject this type into your classes, if that reads better for your codebase. 187 | 188 | ```csharp 189 | public class MyLoginService 190 | { 191 | public MyLoginService(PublisherOf customerLoggedInEventPublisher) 192 | { 193 | _customerLoggedInEventPublisher = customerLoggedInEventPublisher; 194 | } 195 | 196 | public void DoStuff() 197 | { 198 | _customerLoggedInEventPublisher.ForEachSubscriber().DoThis(); 199 | } 200 | } 201 | ``` 202 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /TomLonghurst.AllOf/SourceGenerator/AllOfGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.Text; 4 | using TomLonghurst.AllOf.Extensions; 5 | using TomLonghurst.AllOf.Models; 6 | using TomLonghurst.AllOf.SourceGenerator.Helpers; 7 | 8 | namespace TomLonghurst.AllOf.SourceGenerator; 9 | 10 | [Generator] 11 | public class AllOfGenerator : ISourceGenerator 12 | { 13 | private const string VoidKeyword = "void"; 14 | 15 | private readonly List _typesWritten = new(); 16 | 17 | public void Initialize(GeneratorInitializationContext context) 18 | { 19 | context.RegisterForSyntaxNotifications(() => new AllOfSyntaxReceiver()); 20 | } 21 | 22 | public void Execute(GeneratorExecutionContext context) 23 | { 24 | if (context.SyntaxContextReceiver is not AllOfSyntaxReceiver syntaxReciever) 25 | { 26 | return; 27 | } 28 | 29 | #if DEBUG 30 | if (!System.Diagnostics.Debugger.IsAttached) 31 | { 32 | //System.Diagnostics.Debugger.Launch(); 33 | } 34 | #endif 35 | 36 | var source = GenerateSource(context, syntaxReciever); 37 | 38 | context.AddSource("AllOf.generated", SourceText.From(source, Encoding.UTF8)); 39 | } 40 | 41 | /// 42 | /// Your Main comment 43 | /// 44 | /// This is line 2 45 | /// 46 | private string GenerateSource(GeneratorExecutionContext context, AllOfSyntaxReceiver syntaxReciever) 47 | { 48 | var codeWriter = new CodeGenerationTextWriter(); 49 | 50 | codeWriter.WriteLine(context.GetUsingStatementsForTypes( 51 | syntaxReciever.Identified.Select(d => d.InterfaceType), 52 | typeof(DependencyInjectionExtensions), 53 | typeof(IAllOf), 54 | typeof(AllOf<>), 55 | typeof(AllOfImpl<>), 56 | typeof(IEnumerable<>), 57 | typeof(Enumerable), 58 | typeof(string), 59 | typeof(Task), 60 | typeof(Task<>) 61 | )); 62 | codeWriter.WriteLine(); 63 | 64 | 65 | foreach (var identifiedDecorator in syntaxReciever.Identified.DistinctBy(d => d.InterfaceType)) 66 | { 67 | var typeSymbol = identifiedDecorator.InterfaceType; 68 | 69 | var interfaceShortName = typeSymbol.ToDisplayString(SymbolDisplayFormats.GenericBase).Split('.').Last(); 70 | var interfaceLongName = typeSymbol.ToDisplayString(SymbolDisplayFormats.NamespaceAndType); 71 | 72 | var guid = Guid.NewGuid().ToString("N"); 73 | 74 | var generics = typeSymbol.TypeParameters.Any() 75 | ? $"<{string.Join(", ", typeSymbol.ToDisplayString(SymbolDisplayFormats.NamespaceAndType))}>" 76 | : string.Empty; 77 | 78 | if (_typesWritten.Contains(interfaceLongName)) 79 | { 80 | continue; 81 | } 82 | 83 | _typesWritten.Add(interfaceLongName); 84 | 85 | codeWriter.WriteLine($"namespace {typeSymbol.ContainingNamespace}"); 86 | codeWriter.WriteLine("{"); 87 | 88 | codeWriter.WriteLine($"internal class AllOf_{interfaceShortName}_Impl_{guid}{generics} : {interfaceLongName}"); 89 | codeWriter.WriteLine("{"); 90 | codeWriter.WriteLine($"private readonly IEnumerable<{interfaceLongName}> Items;"); 91 | codeWriter.WriteLine($"public AllOf_{interfaceShortName}_Impl_{guid}(IEnumerable<{interfaceLongName}> items)"); 92 | codeWriter.WriteLine("{"); 93 | codeWriter.WriteLine("Items = items;"); 94 | codeWriter.WriteLine("}"); 95 | codeWriter.WriteLine(); 96 | 97 | foreach (var methodSymbol in identifiedDecorator.MethodsInInterface) 98 | { 99 | var parametersWithType = methodSymbol.Parameters.Select(p => 100 | $"{GetRef(p.RefKind)} {string.Join(" ", p.RefCustomModifiers)} {string.Join(" ", p.CustomModifiers)} {p.Type.ToDisplayString(SymbolDisplayFormats.NamespaceAndType)} {p.Name}".Trim()); 101 | 102 | var returnType = methodSymbol.ReturnsVoid 103 | ? VoidKeyword 104 | : methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormats.NamespaceAndType) ; 105 | 106 | codeWriter.WriteLine("/// "); 107 | codeWriter.WriteLine($"/// Calls {methodSymbol.Name} on each item in the "); 108 | codeWriter.WriteLine("/// "); 109 | codeWriter.WriteLine( $"public {returnType} {methodSymbol.Name}{GetGenericType(methodSymbol)}({string.Join(", ", parametersWithType)})"); 110 | codeWriter.WriteLine("{"); 111 | GenerateBody(codeWriter, methodSymbol); 112 | codeWriter.WriteLine("}"); 113 | codeWriter.WriteLine(); 114 | } 115 | 116 | codeWriter.WriteLine("}"); 117 | 118 | codeWriter.WriteLine($"internal partial class {nameof(AllOfData)}"); 119 | codeWriter.WriteLine("{"); 120 | codeWriter.WriteLine($"[System.Runtime.CompilerServices.ModuleInitializer]"); 121 | codeWriter.WriteLine($"internal static void Register{Guid.NewGuid():N}()"); 122 | codeWriter.WriteLine("{"); 123 | codeWriter.WriteLine($"{typeof(AllOfData).Namespace}.{nameof(AllOfData)}.{nameof(AllOfData.Implementations)}.TryAdd(typeof({interfaceLongName}), typeof(AllOf_{interfaceShortName}_Impl_{guid}{generics}));"); 124 | codeWriter.WriteLine("}"); 125 | codeWriter.WriteLine("}"); 126 | 127 | codeWriter.WriteLine("}"); 128 | codeWriter.WriteLine(); 129 | } 130 | 131 | return codeWriter.ToString(); 132 | } 133 | 134 | private static void GenerateBody(TextWriter codeWriter, IMethodSymbol methodSymbol) 135 | { 136 | var parameters = methodSymbol.Parameters.Select( 137 | p => $"{GetRef(p.RefKind)} {p.Name}".Trim() 138 | ); 139 | 140 | if (methodSymbol.ReturnsVoid) 141 | { 142 | codeWriter.WriteLine("foreach (var item in Items)"); 143 | codeWriter.WriteLine("{"); 144 | codeWriter.WriteLine($"item.{methodSymbol.Name}({string.Join(", ", parameters)});"); 145 | codeWriter.WriteLine("}"); 146 | } 147 | else if(methodSymbol.ReturnType.ToDisplayString(SymbolDisplayFormats.NamespaceAndType) == typeof(Task).FullName) 148 | { 149 | codeWriter.WriteLine($"return Task.WhenAll(Items.Select(item => item.{methodSymbol.Name}({string.Join(", ", parameters)})));"); 150 | } 151 | else 152 | { 153 | codeWriter.WriteLine($"var tasks = Items.Select(item => item.{methodSymbol.Name}({string.Join(", ", parameters)}).AsTask());"); 154 | codeWriter.WriteLine("return new ValueTask(Task.WhenAll(tasks));"); 155 | } 156 | } 157 | 158 | private static string GetGenericType(IMethodSymbol method) 159 | { 160 | if (method.TypeParameters.Any() != true) 161 | { 162 | return string.Empty; 163 | } 164 | 165 | var genericTypes = method.TypeParameters.Select(x => x.Name); 166 | return $"<{string.Join(", ", genericTypes)}>"; 167 | } 168 | 169 | private static string GetRef(RefKind refKind) 170 | { 171 | return refKind switch 172 | { 173 | RefKind.None => string.Empty, 174 | RefKind.Ref => "ref", 175 | RefKind.Out => "out", 176 | RefKind.In => "in", 177 | _ => throw new ArgumentOutOfRangeException(nameof(refKind), refKind, null) 178 | }; 179 | } 180 | } -------------------------------------------------------------------------------- /TomLonghurst.AllOf.UnitTests/Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Moq; 4 | using TomLonghurst.AllOf.Extensions; 5 | using TomLonghurst.AllOf.Models; 6 | using TomLonghurst.AllOf.UnitTests.DependentProject; 7 | using TomLonghurst.AllOf.UnitTests.TestModels.Classes; 8 | using TomLonghurst.AllOf.UnitTests.TestModels.Interfaces; 9 | 10 | namespace TomLonghurst.AllOf.UnitTests; 11 | 12 | /** 13 | * 14 | */ 15 | public class Tests 16 | { 17 | [Test] 18 | public void VoidTest() 19 | { 20 | var serviceProvider = new ServiceCollection() 21 | .AddSingleton() 22 | .AddSingleton() 23 | .AddSingleton() 24 | .AddAllOfs() 25 | .BuildServiceProvider(); 26 | 27 | var stringBuilder = new StringBuilder(); 28 | 29 | var myInterface = serviceProvider.GetRequiredService>(); 30 | 31 | Assert.That(myInterface.GetType().Name, Is.EqualTo("AllOfImpl`1")); 32 | 33 | myInterface.OnEach().Blah(str => stringBuilder.Append(str + " ")); 34 | 35 | Assert.That(stringBuilder.ToString(), Is.EqualTo("MyTestClass MyTestClass2 MyTestClass3 ")); 36 | } 37 | 38 | [Test] 39 | public async Task AsyncTest() 40 | { 41 | var serviceProvider = new ServiceCollection() 42 | .AddSingleton() 43 | .AddSingleton() 44 | .AddSingleton() 45 | .AddAllOfs() 46 | .BuildServiceProvider(); 47 | 48 | var sbLock = new object(); 49 | 50 | var stringBuilder = new StringBuilder(); 51 | 52 | var myInterface = serviceProvider.GetRequiredService>(); 53 | 54 | Assert.That(myInterface.GetType().Name, Is.EqualTo("AllOfImpl`1")); 55 | 56 | var task = myInterface.OnEach().BlahAsync(async str => 57 | { 58 | await Task.Delay(1000); 59 | lock (sbLock) 60 | { 61 | stringBuilder.Append(str + " "); 62 | } 63 | }); 64 | 65 | // We didn't await so no time for the StringBuilder to be called 66 | 67 | Assert.That(stringBuilder.ToString(), Is.EqualTo("")); 68 | 69 | await task; 70 | 71 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyAsyncTestClass")); 72 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyAsyncTestClass2")); 73 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyAsyncTestClass3")); 74 | } 75 | 76 | [Test] 77 | public async Task ValueTaskAsyncTest() 78 | { 79 | var serviceProvider = new ServiceCollection() 80 | .AddSingleton() 81 | .AddSingleton() 82 | .AddSingleton() 83 | .AddAllOfs() 84 | .BuildServiceProvider(); 85 | 86 | var stringBuilder = new StringBuilder(); 87 | 88 | var myInterface = serviceProvider.GetRequiredService>(); 89 | 90 | Assert.That(myInterface.GetType().Name, Is.EqualTo("AllOfImpl`1")); 91 | 92 | var sbLock = new object(); 93 | 94 | var task = myInterface.OnEach().BlahAsync(async str => 95 | { 96 | await Task.Delay(100); 97 | lock (sbLock) 98 | { 99 | stringBuilder.Append(str + " "); 100 | } 101 | }); 102 | 103 | // We didn't await so no time for the StringBuilder to be called 104 | 105 | Assert.That(stringBuilder.ToString(), Is.EqualTo("")); 106 | 107 | await task; 108 | 109 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyValueTaskAsyncTestClass")); 110 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyValueTaskAsyncTestClass2")); 111 | Assert.That(stringBuilder.ToString(), Contains.Substring("MyValueTaskAsyncTestClass3")); 112 | } 113 | 114 | [Test] 115 | public void MoqTest() 116 | { 117 | var mock1 = new Mock(); 118 | var mock2 = new Mock(); 119 | var mock3 = new Mock(); 120 | 121 | var services = new ServiceCollection() 122 | .AddTransient(provider => mock1.Object) 123 | .AddScoped(provider => mock2.Object) 124 | .AddSingleton(provider => mock3.Object) 125 | .AddAllOfs() 126 | .BuildServiceProvider(); 127 | 128 | var scope = services.CreateScope().ServiceProvider; 129 | scope.GetRequiredService>().OnEach().Blah(str => {}); 130 | 131 | mock1.Verify(x => x.Blah(It.IsAny>()), Times.Once); 132 | mock2.Verify(x => x.Blah(It.IsAny>()), Times.Once); 133 | mock3.Verify(x => x.Blah(It.IsAny>()), Times.Once); 134 | 135 | scope.GetRequiredService>().OnEach().Blah(str => {}); 136 | 137 | mock1.Verify(x => x.Blah(It.IsAny>()), Times.Exactly(2)); 138 | mock2.Verify(x => x.Blah(It.IsAny>()), Times.Exactly(2)); 139 | mock3.Verify(x => x.Blah(It.IsAny>()), Times.Exactly(2)); 140 | } 141 | 142 | [Test] 143 | public void DependentProjectClass() 144 | { 145 | var serviceProvider = new ServiceCollection() 146 | .AddSingleton() 147 | .AddSingleton() 148 | .AddSingleton() 149 | .AddAllOfs() 150 | .BuildServiceProvider(); 151 | 152 | var myInterface = serviceProvider.GetRequiredService>(); 153 | 154 | Assert.That(myInterface.GetType().Name, Is.EqualTo("AllOfImpl`1")); 155 | 156 | var result = 1; 157 | 158 | myInterface.OnEach().MyDependentMethod(ref result); 159 | 160 | Assert.That(result, Is.EqualTo(123)); 161 | } 162 | 163 | [Test] 164 | public void ConstructorUsingInterfaceWithoutAttribute() 165 | { 166 | var serviceProvider = new ServiceCollection() 167 | .AddSingleton() 168 | .AddSingleton() 169 | .AddAllOfs() 170 | .BuildServiceProvider(); 171 | 172 | var allOf = serviceProvider.GetRequiredService>(); 173 | 174 | Assert.That(allOf, Is.Not.Null); 175 | 176 | var implementation = allOf.OnEach(); 177 | 178 | Assert.That(implementation, Is.Not.Null); 179 | 180 | var constructorClass = serviceProvider.GetRequiredService(); 181 | 182 | Assert.That(constructorClass, Is.Not.Null); 183 | Assert.That(constructorClass.MyTestInterface.Items, Is.Not.Null); 184 | Assert.That(constructorClass.MyTestInterface.OnEach(), Is.Not.Null); 185 | } 186 | 187 | [Test] 188 | public void ConstructorWithAllOfWrapper() 189 | { 190 | var serviceProvider = new ServiceCollection() 191 | .AddSingleton() 192 | .AddSingleton() 193 | .AddSingleton(typeof(PublisherOf<>), typeof(PublisherOfImpl<>)) 194 | .AddAllOfs() 195 | .BuildServiceProvider(); 196 | 197 | var allOf = serviceProvider.GetRequiredService>(); 198 | 199 | Assert.That(allOf, Is.Not.Null); 200 | 201 | var implementation = allOf.OnEach(); 202 | 203 | Assert.That(implementation, Is.Not.Null); 204 | 205 | var constructorClass = serviceProvider.GetRequiredService(); 206 | 207 | Assert.That(constructorClass, Is.Not.Null); 208 | Assert.That(constructorClass.Publisher, Is.Not.Null); 209 | Assert.That(constructorClass.Publisher.ForEachSubscriber(), Is.Not.Null); 210 | } 211 | 212 | 213 | } 214 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------