├── .gitattributes ├── SimpleFactoryGenerator.Tests.Other ├── IProductCrossAssembly.cs ├── Product2InOtherAssembly.cs ├── Product1InOtherAssembly.cs ├── SimpleFactoryGenerator.Tests.Other.csproj └── ProductCrossAssemblyAttribute.cs ├── SimpleFactoryGenerator ├── ITags.cs ├── ProductAttribute.cs ├── ISimpleFactory.cs ├── SimpleFactoryGenerator.csproj ├── SimpleFactory.cs └── Extensions.cs ├── SimpleFactoryGenerator.SourceGenerator ├── SimpleFactoryGenerator.SourceGenerator.csproj ├── FactoryInfo.cs ├── ProductInfo.cs ├── Extensions.cs ├── ImportTypeTemplate.cs ├── TemplateExtensions.cs ├── Generator.cs ├── DiagnosticDescriptors.cs └── AttributeItem.cs ├── SimpleFactoryGenerator.Tests ├── Product2InOtherAssembly.cs ├── Product1InThisAssembly.cs ├── SimpleFactoryGenerator.Tests.csproj └── SimpleFactoryTests.cs ├── LICENSE ├── Directory.Build.props ├── SimpleFactoryGenerator.sln ├── README.zh-CN.md ├── README.md ├── .gitignore └── .editorconfig /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests.Other/IProductCrossAssembly.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleFactoryGenerator.Tests.Other; 2 | 3 | public interface IProductCrossAssembly 4 | { 5 | string Name { get; } 6 | } 7 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/ITags.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleFactoryGenerator; 2 | 3 | public interface ITags 4 | { 5 | int Count { get; } 6 | 7 | bool Contains(string name); 8 | 9 | T GetValue(string name); 10 | } 11 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests.Other/Product2InOtherAssembly.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleFactoryGenerator.Tests.Other; 2 | 3 | [ProductCrossAssembly(nameof(Product2InOtherAssembly))] 4 | internal class Product2InOtherAssembly : IProductCrossAssembly 5 | { 6 | public string Name { get; } 7 | 8 | public Product2InOtherAssembly(string name) => Name = name; 9 | } 10 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/SimpleFactoryGenerator.SourceGenerator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/FactoryInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace SimpleFactoryGenerator.SourceGenerator; 4 | 5 | internal class FactoryInfo 6 | { 7 | public string InterfaceType { get; set; } = null!; 8 | 9 | public string LabelType { get; set; } = null!; 10 | 11 | public IReadOnlyCollection Items { get; set; } = null!; 12 | } 13 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests/Product2InOtherAssembly.cs: -------------------------------------------------------------------------------- 1 | using SimpleFactoryGenerator.Tests.Other; 2 | 3 | namespace SimpleFactoryGenerator.Tests; 4 | 5 | [ProductCrossAssembly(nameof(Product2InOtherAssembly))] 6 | internal class Product2InOtherAssembly : IProductCrossAssembly 7 | { 8 | public string Name { get; } 9 | 10 | public Product2InOtherAssembly(string name) => Name = name; 11 | } 12 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests.Other/Product1InOtherAssembly.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleFactoryGenerator.Tests.Other; 2 | 3 | [ProductCrossAssembly(nameof(Product1InOtherAssembly))] 4 | internal class Product1InOtherAssembly : IProductCrossAssembly 5 | { 6 | public string Name { get; } 7 | 8 | public Product1InOtherAssembly(string name) => Name = name; 9 | } 10 | 11 | public class TestAttribute(int key) : ProductAttribute(key) 12 | { 13 | } 14 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests.Other/SimpleFactoryGenerator.Tests.Other.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests/Product1InThisAssembly.cs: -------------------------------------------------------------------------------- 1 | using SimpleFactoryGenerator.Tests.Other; 2 | 3 | namespace SimpleFactoryGenerator.Tests; 4 | 5 | [ProductCrossAssembly(key: nameof(Product1InThisAssembly), when: "text.dirty", Key = "ctrl+s", Description = "保存文件")] 6 | [ProductCrossAssembly("shell.saveAll", when: "any(text.dirty)", Key = "ctrl+shift+s", Description = "保存所有文件")] 7 | internal class Product1InThisAssembly : IProductCrossAssembly 8 | { 9 | public string Name { get; } 10 | 11 | public Product1InThisAssembly(string name) => Name = name; 12 | } 13 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/ProductAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleFactoryGenerator; 4 | 5 | /// 6 | /// Place this attribute onto a type to cause it to be considered a product of simple-factory pattern. 7 | /// 8 | /// The type of the feed used to produce products. 9 | /// The type of the product. 10 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 11 | public class ProductAttribute : Attribute where TProduct : class 12 | { 13 | public ProductAttribute(TKey key) 14 | { 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests.Other/ProductCrossAssemblyAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleFactoryGenerator.Tests.Other; 4 | 5 | public class ProductCrossAssemblyAttribute : ProductAttribute 6 | { 7 | public string Key { get; set; } 8 | 9 | public string Description { get; set; } = string.Empty; 10 | 11 | public string Name { get; set; } = "10086"; 12 | 13 | public int RetryCount { get; set; } = 3; 14 | 15 | public long Size { get; set; } 16 | 17 | public StringSplitOptions SplitOptions { get; set; } = StringSplitOptions.RemoveEmptyEntries; 18 | 19 | public ProductCrossAssemblyAttribute(string key, string when = "") : base(key) 20 | { 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Dingping Zhang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/ProductInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.CodeAnalysis; 3 | 4 | namespace SimpleFactoryGenerator.SourceGenerator; 5 | 6 | internal class ProductInfo 7 | { 8 | public bool IsPrivate { get; set; } 9 | 10 | public string LabelValue { get; set; } = null!; 11 | 12 | public string ClassType { get; set; } = null!; 13 | 14 | public IReadOnlyList<(string Key, string Value)> Tags { get; set; } = null!; 15 | 16 | public static ProductInfo From(AttributeItem item) 17 | { 18 | return new ProductInfo 19 | { 20 | IsPrivate = IsPrivateClass(item.ClassType), 21 | LabelValue = item.LabelValue, 22 | ClassType = GetClassDeclaration(item.ClassType), 23 | Tags = item.Tags, 24 | }; 25 | } 26 | 27 | private static bool IsPrivateClass(ISymbol symbol) 28 | { 29 | return symbol.DeclaredAccessibility is Accessibility.Private; 30 | } 31 | 32 | private static string GetClassDeclaration(ISymbol symbol) 33 | { 34 | return IsPrivateClass(symbol) 35 | ? $"{symbol.ContainingType.ToDisplayString()}+{symbol.Name}" 36 | : symbol.ToDeclaration(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/ISimpleFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SimpleFactoryGenerator; 4 | 5 | public delegate TProduct ProductCreator(Type productType, ITags tags, TKey key, object?[] args); 6 | 7 | /// 8 | /// Represents a simple-factory. 9 | /// 10 | /// The type of the feed used to produce products. 11 | /// The type of the product. 12 | public interface ISimpleFactory 13 | { 14 | /// 15 | /// Replaces this factory's internal creator. 16 | /// 17 | /// Creator for creating instances based on type. 18 | /// Returns itself. 19 | ISimpleFactory WithCreator(ProductCreator creator); 20 | 21 | /// 22 | /// Creates a product instance by the specified key. 23 | /// 24 | /// The specified key. 25 | /// The arguments required by the constructor that creates this instance. 26 | /// Returns a instance. 27 | TProduct Create(TKey key, params object?[] args); 28 | } 29 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 2.12 5 | Dingping Zhang 6 | 0.8.0 7 | Copyright (c) 2022 Dingping Zhang 8 | https://github.com/DingpingZhang/SimpleFactoryGenerator 9 | https://github.com/DingpingZhang/SimpleFactoryGenerator 10 | true 11 | MIT 12 | en-US 13 | A simple factory source generator that enables the pattern to not violate the open-close principle. 14 | design-pattern;design;pattern;simple-factory;factory;solid principle;open-close-principle 15 | $(NoWarn);1701;1702;CS1591;NU1701 16 | true 17 | preview 18 | true 19 | true 20 | True 21 | enable 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests/SimpleFactoryGenerator.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net60 5 | false 6 | preview 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/SimpleFactoryGenerator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | True 7 | README.md 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | TextTemplatingFileGenerator 22 | ISimpleFactory.generic.cs 23 | 24 | 25 | TextTemplatingFileGenerator 26 | SimpleFactoryImpl.generic.cs 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | True 37 | True 38 | ISimpleFactory.generic.tt 39 | 40 | 41 | True 42 | True 43 | SimpleFactoryImpl.generic.tt 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.CodeAnalysis; 3 | 4 | namespace SimpleFactoryGenerator.SourceGenerator; 5 | 6 | internal static class Extensions 7 | { 8 | public static string ToDisplayValue(this TypedConstant constant) 9 | { 10 | /* 11 | * Ref to: https://stackoverflow.com/a/25859321 12 | * 13 | * TODO: 14 | * The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: 15 | * 16 | * 1. One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. 17 | * 2. The type object. 18 | * 3. The type System.Type. 19 | * 4. An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Attribute specification). 20 | * 5. Single-dimensional arrays of the above types. (emphasis added by me) 21 | */ 22 | 23 | if (constant.Type!.ToDeclaration() == "string") 24 | { 25 | return $"\"{constant.Value}\""; 26 | } 27 | 28 | if (constant.Kind is TypedConstantKind.Enum) 29 | { 30 | return $"({constant.Type!.ToDeclaration()}){constant.Value}"; 31 | } 32 | 33 | return $"{constant.Value}"; 34 | } 35 | 36 | public static string ToDeclaration(this ISymbol symbol) 37 | { 38 | return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); 39 | } 40 | 41 | public static IEnumerable GetSelfAndBaseTypes(this ITypeSymbol symbol) 42 | { 43 | ITypeSymbol? baseType = symbol; 44 | while (baseType is not null) 45 | { 46 | yield return baseType; 47 | 48 | baseType = baseType.BaseType; 49 | } 50 | } 51 | 52 | public static bool EqualAttribute(this INamedTypeSymbol expected, INamedTypeSymbol? actual) 53 | { 54 | return actual is { IsGenericType: true, IsUnboundGenericType: false } && 55 | expected.Equals(actual.ConstructUnboundGenericType(), SymbolEqualityComparer.Default) || 56 | expected.Equals(actual, SymbolEqualityComparer.Default); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/SimpleFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SimpleFactoryGenerator; 5 | 6 | /// 7 | /// Represents the builder of simple-factory. 8 | /// 9 | public static class SimpleFactory 10 | { 11 | /// 12 | /// Gets a simple-factory by the specified and type. 13 | /// 14 | /// The type of the feed used to produce products. 15 | /// The type of the product. 16 | /// Returns a simple-factory used to create the instance by the specified . 17 | public static ISimpleFactory For() 18 | { 19 | return new SimpleFactory(); 20 | } 21 | } 22 | 23 | /// 24 | /// Represents a simple-factory implementation. 25 | /// 26 | /// The type of the feed used to produce products. 27 | /// The type of the product. 28 | public class SimpleFactory : ISimpleFactory 29 | { 30 | private static readonly Dictionary ProductStorage = new(); 31 | private static readonly Dictionary TagStorage = new(); 32 | 33 | public static IReadOnlyDictionary Products => ProductStorage; 34 | 35 | public static IReadOnlyDictionary Tags => TagStorage; 36 | 37 | public static void Register(TKey key, Type type, ITags tags) 38 | { 39 | ProductStorage[key] = type; 40 | TagStorage[key] = tags; 41 | } 42 | 43 | private static TProduct DefaultCreator(Type type, ITags tags, TKey key, object?[] args) 44 | { 45 | return (TProduct)Activator.CreateInstance(type, args); 46 | } 47 | 48 | private ProductCreator _creator = DefaultCreator; 49 | 50 | internal SimpleFactory() { } 51 | 52 | /// 53 | public ISimpleFactory WithCreator(ProductCreator creator) 54 | { 55 | _creator = creator; 56 | return this; 57 | } 58 | 59 | /// 60 | public TProduct Create(TKey key, params object?[] args) 61 | { 62 | return _creator(Products[key], Tags[key], key, args); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/ImportTypeTemplate.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using static SimpleFactoryGenerator.SourceGenerator.TemplateExtensions; 3 | 4 | namespace SimpleFactoryGenerator.SourceGenerator; 5 | 6 | internal static class ImportTypeTemplate 7 | { 8 | public static string Generate(IEnumerable infos) 9 | { 10 | return $@" 11 | #nullable enable 12 | 13 | #if !NET5_0_OR_GREATER 14 | namespace System.Runtime.CompilerServices 15 | {{ 16 | [AttributeUsage(AttributeTargets.Method, Inherited = false)] 17 | internal sealed class ModuleInitializerAttribute : Attribute {{ }} 18 | }} 19 | #endif 20 | 21 | namespace SimpleFactoryGenerator.Implementation 22 | {{ 23 | internal static class ModuleInitializer 24 | {{ 25 | #pragma warning disable CA2255 // The 'ModuleInitializer' attribute should not be used in libraries 26 | [System.Runtime.CompilerServices.ModuleInitializer] 27 | #pragma warning restore CA2255 // The 'ModuleInitializer' attribute should not be used in libraries 28 | public static void Initialize() 29 | {{ 30 | {infos.For(x => $@" 31 | {x.Items.For(item => Text(item.IsPrivate ? $@" 32 | SimpleFactory<{x.LabelType}, {x.InterfaceType}>.Register({item.LabelValue}, System.Type.GetType(""{item.ClassType}""), {GetTagsCode(item.Tags)}); 33 | " : $@" 34 | SimpleFactory<{x.LabelType}, {x.InterfaceType}>.Register({item.LabelValue}, typeof({item.ClassType}), {GetTagsCode(item.Tags)}); 35 | "))} 36 | 37 | ")} 38 | }} 39 | 40 | private sealed class Tags : SimpleFactoryGenerator.ITags 41 | {{ 42 | public static readonly SimpleFactoryGenerator.ITags Empty = new Tags(new System.Collections.Generic.Dictionary()); 43 | 44 | private readonly System.Collections.Generic.IReadOnlyDictionary _storage; 45 | 46 | public int Count => _storage.Count; 47 | 48 | public Tags(System.Collections.Generic.IReadOnlyDictionary storage) => _storage = storage; 49 | 50 | public bool Contains(string name) => _storage.ContainsKey(name); 51 | 52 | public T GetValue(string name) => (T)_storage[name]!; 53 | }} 54 | }} 55 | }} 56 | ".FormatCode(); 57 | } 58 | 59 | private static string GetTagsCode(IReadOnlyList<(string Key, string Value)> tags) 60 | { 61 | return tags.Count is 0 62 | ? "Tags.Empty" 63 | : $@"new Tags(new System.Collections.Generic.Dictionary{{ {tags.Join(", ", x => $@"{{ ""{x.Key}"", {x.Value} }}")} }})"; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/TemplateExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.RegularExpressions; 5 | 6 | namespace SimpleFactoryGenerator.SourceGenerator; 7 | 8 | public static class TemplateExtensions 9 | { 10 | public const string RemoveLineIfEmpty = " "; 11 | public const string KeepLineIfEmpty = ""; 12 | public const string LineTrimmedFlag = "#\"#"; 13 | 14 | private static readonly int NewLineLength = Environment.NewLine.Length; 15 | private static readonly Regex WhiteSpaceLineRegex = new($@"{Environment.NewLine}( +?{Environment.NewLine})+", RegexOptions.Compiled); 16 | 17 | public static string For(this IEnumerable self, Func callback, string fallbackIfEmpty = RemoveLineIfEmpty) 18 | { 19 | return self.For((item, _) => callback(item), fallbackIfEmpty); 20 | } 21 | 22 | public static string For(this IEnumerable self, Func callback, string fallbackIfEmpty = RemoveLineIfEmpty) 23 | { 24 | var list = self.ToList(); 25 | if (list.Count == 0) 26 | { 27 | return fallbackIfEmpty; 28 | } 29 | 30 | return string.Join(Environment.NewLine, list.Select((item, index) => callback(item, index).TrimNewLine())); 31 | } 32 | 33 | public static string Join(this IEnumerable self, string separator = "", Func? callback = null) 34 | { 35 | return string.Join(separator, self.Select(item => callback?.Invoke(item) ?? item?.ToString() ?? KeepLineIfEmpty)); 36 | } 37 | 38 | public static string If(this string? self, Func ifTrueCallback, string? ifFalseText = KeepLineIfEmpty) 39 | { 40 | return string.IsNullOrEmpty(self) 41 | ? ifFalseText?.TrimNewLine() ?? string.Empty 42 | : ifTrueCallback(self!.TrimNewLine()).TrimNewLine(); 43 | } 44 | 45 | public static string FormatCode(this string text) 46 | { 47 | text = text 48 | .Replace(LineTrimmedFlag, string.Empty) 49 | .TrimStart(Environment.NewLine.ToCharArray()); 50 | 51 | return WhiteSpaceLineRegex.Replace(text, Environment.NewLine); 52 | } 53 | 54 | public static string Text(string? text) => text.TrimNewLine(); 55 | 56 | private static string TrimNewLine(this string? text) 57 | { 58 | if (string.IsNullOrEmpty(text)) 59 | { 60 | return string.Empty; 61 | } 62 | 63 | int start = text!.StartsWith(Environment.NewLine) ? NewLineLength : 0; 64 | int length = text.EndsWith(Environment.NewLine) 65 | ? text.Length - start - NewLineLength 66 | : text.Length - start; 67 | 68 | return $"{LineTrimmedFlag}{text.Substring(start, length)}{LineTrimmedFlag}"; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32112.339 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleFactoryGenerator", "SimpleFactoryGenerator\SimpleFactoryGenerator.csproj", "{9A2F3B94-8D24-4F20-A1B9-570206483A12}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleFactoryGenerator.SourceGenerator", "SimpleFactoryGenerator.SourceGenerator\SimpleFactoryGenerator.SourceGenerator.csproj", "{052E3C8D-6F9C-4731-BFB2-97C52E1F180F}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{524A5560-BF11-4B8A-8622-C07275CDBB75}" 11 | ProjectSection(SolutionItems) = preProject 12 | .editorconfig = .editorconfig 13 | .gitattributes = .gitattributes 14 | .gitignore = .gitignore 15 | Directory.Build.props = Directory.Build.props 16 | LICENSE = LICENSE 17 | README.md = README.md 18 | EndProjectSection 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleFactoryGenerator.Tests", "SimpleFactoryGenerator.Tests\SimpleFactoryGenerator.Tests.csproj", "{4FE5F93B-F641-408C-862A-85BFE61D0D8B}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimpleFactoryGenerator.Tests.Other", "SimpleFactoryGenerator.Tests.Other\SimpleFactoryGenerator.Tests.Other.csproj", "{2ACBE79E-FAB5-47C0-8FB9-129D7DA6542C}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {9A2F3B94-8D24-4F20-A1B9-570206483A12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {9A2F3B94-8D24-4F20-A1B9-570206483A12}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {9A2F3B94-8D24-4F20-A1B9-570206483A12}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {9A2F3B94-8D24-4F20-A1B9-570206483A12}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {052E3C8D-6F9C-4731-BFB2-97C52E1F180F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {052E3C8D-6F9C-4731-BFB2-97C52E1F180F}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {052E3C8D-6F9C-4731-BFB2-97C52E1F180F}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {052E3C8D-6F9C-4731-BFB2-97C52E1F180F}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {4FE5F93B-F641-408C-862A-85BFE61D0D8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {4FE5F93B-F641-408C-862A-85BFE61D0D8B}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {4FE5F93B-F641-408C-862A-85BFE61D0D8B}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {4FE5F93B-F641-408C-862A-85BFE61D0D8B}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {2ACBE79E-FAB5-47C0-8FB9-129D7DA6542C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {2ACBE79E-FAB5-47C0-8FB9-129D7DA6542C}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {2ACBE79E-FAB5-47C0-8FB9-129D7DA6542C}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {2ACBE79E-FAB5-47C0-8FB9-129D7DA6542C}.Release|Any CPU.Build.0 = Release|Any CPU 46 | EndGlobalSection 47 | GlobalSection(SolutionProperties) = preSolution 48 | HideSolutionNode = FALSE 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {8A6C8AB0-C2CB-404B-93D4-F933BE04724A} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.Tests/SimpleFactoryTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Shouldly; 4 | using SimpleFactoryGenerator.Tests.Other; 5 | using Xunit; 6 | 7 | namespace SimpleFactoryGenerator.Tests; 8 | 9 | public class SimpleFactoryTests 10 | { 11 | [Fact(DisplayName = "It should support product classes across assemblies.")] 12 | public void SupportCrossAssembly() 13 | { 14 | var products = SimpleFactory.Products; 15 | 16 | products.Count.ShouldBe(4); 17 | products.Values.Contains(typeof(Product1InThisAssembly)).ShouldBeTrue(); 18 | 19 | var product = products["Product1InOtherAssembly"]; 20 | product.Assembly.GetName().Name!.ShouldBe("SimpleFactoryGenerator.Tests.Other"); 21 | } 22 | 23 | [Fact(DisplayName = "it should replace the same key with the type registered later.")] 24 | public void ReplaceWithTypeRegisteredLater() 25 | { 26 | var products = SimpleFactory.Products; 27 | var product = products[nameof(Product2InOtherAssembly)]; 28 | 29 | product.ShouldBe(typeof(Product2InOtherAssembly)); 30 | product.Assembly.GetName().Name!.ShouldNotBe("SimpleFactoryGenerator.Tests.Other"); 31 | } 32 | 33 | [Fact(DisplayName = "it should be create types with parameters.")] 34 | public void CreateWithParameters() 35 | { 36 | var factory = SimpleFactory.For(); 37 | var products = SimpleFactory.Products; 38 | 39 | foreach (var info in products) 40 | { 41 | string name = Guid.NewGuid().ToString(); 42 | bool success = factory.TryCreate(info.Key, out var product, name); 43 | 44 | success.ShouldBeTrue(); 45 | product.GetType().ShouldBe(info.Value); 46 | product.Name.ShouldBe(name); 47 | } 48 | } 49 | 50 | [Fact(DisplayName = "it should support caching.")] 51 | public void SupportCache() 52 | { 53 | int count = 0; 54 | var factory = SimpleFactory.For() 55 | .WithCreator((type, tags, key, args) => 56 | { 57 | count++; 58 | string when = tags.GetValue("when"); 59 | return (IProductCrossAssembly)Activator.CreateInstance(type, args)!; 60 | }) 61 | .WithCache(); 62 | var products = SimpleFactory.Products; 63 | 64 | count.ShouldBe(0); 65 | string name = Guid.NewGuid().ToString(); 66 | _ = factory.CreateAll(name).ToArray(); 67 | count.ShouldBe(products.Count); 68 | 69 | count = 0; 70 | _ = factory.CreateAll(name).ToArray(); 71 | count.ShouldBe(0); 72 | } 73 | 74 | [Fact(DisplayName = "it should clear the cache when the creator is updated.")] 75 | public void ClearCache() 76 | { 77 | var factory = SimpleFactory.For().WithCache(); 78 | var products = SimpleFactory.Products; 79 | 80 | string name = Guid.NewGuid().ToString(); 81 | _ = factory.CreateAll(name).ToArray(); 82 | 83 | int count = 0; 84 | factory = factory.WithCreator((_, _, _, _) => 85 | { 86 | count++; 87 | return null!; 88 | }); 89 | count = 0; 90 | var instances = factory.CreateAll(name).ToArray(); 91 | count.ShouldBe(products.Count); 92 | instances.ShouldAllBe(x => x == null!); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/Generator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Text; 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | using Microsoft.CodeAnalysis.CSharp.Syntax; 7 | using Microsoft.CodeAnalysis.Text; 8 | 9 | namespace SimpleFactoryGenerator.SourceGenerator; 10 | 11 | [Generator] 12 | public class Generator : ISourceGenerator 13 | { 14 | public void Execute(GeneratorExecutionContext context) 15 | { 16 | //System.Diagnostics.Debugger.Launch(); 17 | 18 | if (context.SyntaxReceiver is not SyntaxReceiver receiver) 19 | { 20 | return; 21 | } 22 | 23 | Compilation compilation = context.Compilation; 24 | 25 | if (!AttributeItem.Initialize(compilation)) 26 | { 27 | return; 28 | } 29 | 30 | var attributeItems = receiver.CandidateClasses 31 | .GroupBy(@class => @class.SyntaxTree) 32 | .SelectMany(group => 33 | { 34 | SemanticModel model = compilation.GetSemanticModel(group.Key); 35 | return group 36 | .Select(x => model.GetDeclaredSymbol(x)) 37 | .OfType() 38 | .SelectMany(x => AttributeItem.From(context, x)); 39 | }) 40 | .ToArray(); 41 | 42 | var classSymbols = attributeItems 43 | .Select(x => x.ClassType) 44 | .Distinct(SymbolEqualityComparer.Default) 45 | .OfType() 46 | .ToArray(); 47 | if (!context.CheckNoGenericParameters(classSymbols)) 48 | { 49 | return; 50 | } 51 | 52 | var factoryInfos = GetFactories(context, attributeItems).ToArray(); 53 | if (factoryInfos.Any()) 54 | { 55 | string simpleFactorySource = ImportTypeTemplate.Generate(factoryInfos); 56 | context.AddSource("ImportType.g.cs", SourceText.From(simpleFactorySource, Encoding.UTF8)); 57 | } 58 | } 59 | 60 | public void Initialize(GeneratorInitializationContext context) 61 | { 62 | context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); 63 | } 64 | 65 | private static IEnumerable GetFactories(GeneratorExecutionContext context, IEnumerable attributeItems) 66 | { 67 | var groups = attributeItems.GroupBy(x => x.InterfaceType); 68 | 69 | foreach (var group in groups) 70 | { 71 | var target = group.Key; 72 | var items = group.ToArray(); 73 | var classTypes = items.Select(x => x.ClassType); 74 | if (!context.CheckImplementTargetInterface(target, classTypes)) 75 | { 76 | yield break; 77 | } 78 | 79 | if (!context.CheckTheSameKeyType(items)) 80 | { 81 | yield break; 82 | } 83 | 84 | var keyTypes = items.Select(x => x.LabelType).Distinct(SymbolEqualityComparer.Default).ToArray(); 85 | string labelType = keyTypes[0]!.ToDeclaration(); 86 | string interfaceType = target.ToDeclaration(); 87 | 88 | yield return new FactoryInfo 89 | { 90 | LabelType = labelType, 91 | InterfaceType = interfaceType, 92 | Items = items.Select(ProductInfo.From).ToArray(), 93 | }; 94 | } 95 | } 96 | 97 | private class SyntaxReceiver : ISyntaxReceiver 98 | { 99 | public List CandidateClasses { get; } = new(); 100 | 101 | public void OnVisitSyntaxNode(SyntaxNode syntaxNode) 102 | { 103 | if (syntaxNode is ClassDeclarationSyntax { AttributeLists.Count: > 0 } interfaceDeclarationSyntax) 104 | { 105 | CandidateClasses.Add(interfaceDeclarationSyntax); 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /README.zh-CN.md: -------------------------------------------------------------------------------- 1 | # SimpleFactoryGenerator [![version](https://img.shields.io/nuget/v/SimpleFactoryGenerator.svg)](https://www.nuget.org/packages/SimpleFactoryGenerator) 2 | 3 | [English](./README.md) | 中文 4 | 5 | 本库用于辅助简单工厂模式(Simple Factory Pattern)的实现,即在编译时自动生成简单工厂中的条件分支语句(`switch-case` 或 `if-else`),从而解决该模式违背“开闭原则”([The Open/Closed Principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle))的问题。 6 | 7 | ## 1. 为什么使用? 8 | 9 | 关于简单工厂模式([factory-comparison](https://refactoringguru.cn/design-patterns/factory-comparison))的介绍与使用,此处不予赘述。该模式的一个缺点是:需要维护一个(可能十分巨大)的条件分支结构,用于根据给定的枚举类型创建具体的实例。因此,该模式违背了“对扩展开放,对修改封闭”的设计原则,本仓库解决了这个问题。思路非常简单:设计原则只是为了便于**人类**维护代码的一套经验规则,用于弥补人类思维的一些局限性,那么,只需要将这部分难以维护的代码交给编译器维护,就不存在违背“设计原则”的说法了。 10 | 11 | ## 2. 如何使用? 12 | 13 | 我们先来看一个传统方式实现的简单工厂,以便于对比本仓库所代替的部分: 14 | 15 | ```csharp 16 | public interface IProduct 17 | { 18 | } 19 | 20 | public class Product1 : IProduct 21 | { 22 | } 23 | 24 | public class Product2 : IProduct 25 | { 26 | } 27 | 28 | public class SimpleFactory 29 | { 30 | public IProduct Create(string type) 31 | { 32 | // NOTE: 此处便是违背了开闭原则的分支判断,例:当加入 Product3 后, 33 | // 需要手动在此添加一个分支 `"product_c" => new Product3(),` 34 | return type switch 35 | { 36 | "product_a" => new Product1(), 37 | "product_b" => new Product2(), 38 | _ => throw new IndexOutOfRangeException(), 39 | } 40 | } 41 | } 42 | 43 | // 使用 44 | 45 | var factory = new SimpleFactory(); 46 | IProduct product = factory.Create("product_a"); 47 | ``` 48 | 49 | 在使用本仓库后,将省去 `SimpleFactory` 的编写,而代替的,需要在具体的 `Product` 类型上声明一个 `ProductAttribute`。你已经注意到:该 Attribute 使用了泛型,这需要 [C# 11](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generics-and-attributes) 的支持,为此,你需要使用 VS2022,并在 `*.csproj` 文件中配置:`preview`。 50 | 51 | > 如果你的项目无法配置 C# 11 或使用 VS 2022,导致无法**直接**使用 Generic-Attribute,可以参考 3.1 小节,自定义一个 Attribute 继承自 `ProductAttribute` 即可(在 C# 11 之前允许定义泛型 Attribute,只是无法直接使用而已)。 52 | 53 | ```csharp 54 | // 也可以是 abstract class,或普通的 class,不强制要求是 interface。 55 | public interface IProduct 56 | { 57 | } 58 | 59 | [Product("product_a")] 60 | public class Product1 : IProduct 61 | { 62 | } 63 | 64 | [Product("product_b")] 65 | public class Product2 : IProduct 66 | { 67 | } 68 | 69 | // 使用 70 | 71 | // SimpleFactory 静态类由本仓库提供。 72 | var factory = SimpleFactory 73 | .For() 74 | // .WithCache() 是可选的一个装饰器,其缓存已创建的实例(即多次创建 key 相同的实例,将返回同一个实例。) 75 | .WithCache(); 76 | IProduct product = factory.Create("product_a"); 77 | ``` 78 | 79 | ## 3. 进阶使用 80 | 81 | 其实没有多进阶,就这么简单的一个需求,你还指望有什么高级的东西?也就是使用本库的一些小技巧。 82 | 83 | ### 3.1 自定义 Attribute 84 | 85 | 如果你觉得 `ProductAttribute` 声明太长、太丑、太麻烦(或者无法使用 C# 11 的泛型 Attribute 语法),可以自定义一个 Attribute 继承它,也是生效的,如: 86 | 87 | ```csharp 88 | public class FruitAttribute : ProductAttribute 89 | { 90 | public FruitAttribute(string name) : base(name) 91 | { 92 | } 93 | } 94 | 95 | [Fruit("apple")] 96 | public class Apple : IProduct 97 | { 98 | } 99 | ``` 100 | 101 | ### 3.2 映射到多个目标接口 102 | 103 | 对于同一个具体产品类型,是允许供应给多个不同的目标接口的,如: 104 | 105 | ```csharp 106 | [Animal("老鼠")] 107 | [Food("鸭脖")] 108 | public class Mouse : IAnimal, IFood 109 | { 110 | } 111 | 112 | // Using 113 | var animalFactory = SimpleFactory.For(); 114 | IProduct mouse = animalFactory.Create("老鼠"); 115 | 116 | var foodFactory = SimpleFactory.For(); 117 | IProduct duckNeck = foodFactory.Create("鸭脖"); 118 | ``` 119 | 120 | ### 3.3 传递参数到构造函数 121 | 122 | 若 `Product` 类型的构造函数具有参数,则可以按以下方式进行传递: 123 | 124 | ```csharp 125 | _ = factory.Create("key", arg1, arg2, ...); 126 | ``` 127 | 128 | 由于使用 `factory` 时,往往不能够确定创建类型的构造函数,因而建议所有 `Product` 构造函数的参数列表应该一致。 129 | 130 | 若有需求使得各个 `Product` 的构造函数参数不确定,则建议通过 Ioc 容器来创建: 131 | 132 | ```csharp 133 | var factory = SimpleFactory 134 | .For() 135 | .WithCreator((type, args) => (Product)container.Resolve(type, args)); 136 | 137 | _ = factory.Create(key); 138 | ``` 139 | 140 | 注意:若在 `.WithCache()` 之后使用 `.WithCreator()`,则会导致之前的缓存被清空。(这很合理,一朝天子一朝臣,Creator 都变了,哪里还敢用之前的缓存) 141 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/DiagnosticDescriptors.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | 5 | namespace SimpleFactoryGenerator.SourceGenerator; 6 | 7 | internal static class DiagnosticDescriptors 8 | { 9 | private const string SimpleFactoryGenerator = nameof(SimpleFactoryGenerator); 10 | 11 | public static readonly DiagnosticDescriptor NoGenericParameters = new( 12 | "SFG001", 13 | "The target interface or class must not have generic parameters", 14 | "Interfaces or classes with generic parameters are not supported, consider removing the generic parameters", 15 | SimpleFactoryGenerator, 16 | DiagnosticSeverity.Error, 17 | true); 18 | 19 | public static readonly DiagnosticDescriptor TheSameKeyType = new( 20 | "SFG002", 21 | "Classes with the same target interface must have the same key type", 22 | "If the target interfaces are the same, their key types must also be the same, consider using the same type of key", 23 | SimpleFactoryGenerator, 24 | DiagnosticSeverity.Error, 25 | true); 26 | 27 | public static readonly DiagnosticDescriptor ImplementTargetInterface = new( 28 | "SFG003", 29 | "The class must implement the target interface declared by the attribute", 30 | "The product class must implement the target interface declared on the attribute, consider implementing the interface '{0}' for class '{1}'", 31 | SimpleFactoryGenerator, 32 | DiagnosticSeverity.Error, 33 | true); 34 | 35 | public static readonly DiagnosticDescriptor CorrectAttributeCtor = new( 36 | "SFG004", 37 | "The first argument to the constructor of product attribute must be the 'Key'", 38 | "The product attribute must have at least one parameter that is the Key used to create the product, consider implementing an `{0}({1} key)` constructor", 39 | SimpleFactoryGenerator, 40 | DiagnosticSeverity.Error, 41 | true); 42 | 43 | public static bool CheckImplementTargetInterface(this GeneratorExecutionContext context, ITypeSymbol target, IEnumerable symbols) 44 | { 45 | var invalidClasses = symbols 46 | .Where(item => target.TypeKind is TypeKind.Interface 47 | // Inherited from interface 48 | ? !item.AllInterfaces.Any(@interface => @interface.Equals(target, SymbolEqualityComparer.Default)) 49 | // Inherited from class 50 | : !item.GetSelfAndBaseTypes().Skip(1).Any(@class => !@class.Equals(target, SymbolEqualityComparer.Default))) 51 | .ToList(); 52 | if (!invalidClasses.Any()) 53 | { 54 | return true; 55 | } 56 | 57 | foreach (var invalidClass in invalidClasses) 58 | { 59 | foreach (var location in invalidClass.Locations) 60 | { 61 | context.ReportDiagnostic(Diagnostic.Create(ImplementTargetInterface, location, target.ToDisplayString(), invalidClass.Name)); 62 | } 63 | } 64 | 65 | return false; 66 | } 67 | 68 | public static bool CheckNoGenericParameters(this GeneratorExecutionContext context, IEnumerable symbols) 69 | { 70 | var invalidClasses = symbols 71 | .Where(item => item.TypeParameters.Any()) 72 | .ToList(); 73 | if (!invalidClasses.Any()) 74 | { 75 | return true; 76 | } 77 | 78 | foreach (var location in invalidClasses.SelectMany(item => item.Locations)) 79 | { 80 | context.ReportDiagnostic(Diagnostic.Create(NoGenericParameters, location)); 81 | } 82 | 83 | return false; 84 | } 85 | 86 | public static bool CheckTheSameKeyType(this GeneratorExecutionContext context, IEnumerable items) 87 | { 88 | var issues = items 89 | .GroupBy(x => x.ClassType) 90 | .Select(x => x.ToArray()) 91 | .Where(x => x.Length > 1) 92 | .Where(x => x.Select(y => y.LabelType).Distinct(SymbolEqualityComparer.Default).Count() > 1) 93 | .ToArray(); 94 | if (issues.Length is 0) 95 | { 96 | return true; 97 | } 98 | 99 | var locations = issues.SelectMany(x => x.SelectMany(y => y.ClassType.Locations)).Distinct(); 100 | foreach (var location in locations) 101 | { 102 | context.ReportDiagnostic(Diagnostic.Create(TheSameKeyType, location)); 103 | } 104 | 105 | return false; 106 | } 107 | 108 | public static void ReportCorrectAttributeCtor(this GeneratorExecutionContext context, AttributeData attribute, ITypeSymbol labelType) 109 | { 110 | if (attribute.AttributeClass is null) 111 | { 112 | return; 113 | } 114 | 115 | foreach (var location in attribute.AttributeClass.Locations) 116 | { 117 | context.ReportDiagnostic(Diagnostic.Create(CorrectAttributeCtor, location, attribute.AttributeClass.Name, labelType.ToDisplayString())); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator.SourceGenerator/AttributeItem.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp.Syntax; 5 | 6 | namespace SimpleFactoryGenerator.SourceGenerator; 7 | 8 | internal class AttributeItem 9 | { 10 | private static INamedTypeSymbol ProductSymbol { get; set; } = null!; 11 | 12 | public ITypeSymbol LabelType { get; set; } = null!; 13 | 14 | public ITypeSymbol InterfaceType { get; set; } = null!; 15 | 16 | public INamedTypeSymbol ClassType { get; set; } = null!; 17 | 18 | public string LabelValue { get; set; } = string.Empty; 19 | 20 | public IReadOnlyList<(string Key, string Value)> Tags { get; set; } = null!; 21 | 22 | public static bool Initialize(Compilation compilation) 23 | { 24 | INamedTypeSymbol? productSymbol = compilation 25 | .GetTypeByMetadataName("SimpleFactoryGenerator.ProductAttribute`2")? 26 | .ConstructUnboundGenericType(); 27 | ProductSymbol = productSymbol!; 28 | return productSymbol != null; 29 | } 30 | 31 | public static IEnumerable From(GeneratorExecutionContext context, INamedTypeSymbol classSymbol) 32 | { 33 | foreach (AttributeData attribute in classSymbol.GetAttributes()) 34 | { 35 | INamedTypeSymbol? symbol = attribute.AttributeClass; 36 | 37 | INamedTypeSymbol? productSymbol = symbol?.GetSelfAndBaseTypes() 38 | .OfType() 39 | .FirstOrDefault(ProductSymbol.EqualAttribute); 40 | if (productSymbol is null) 41 | { 42 | continue; 43 | } 44 | 45 | var labelType = GetLabelType(productSymbol); 46 | var ctorArgs = attribute.ConstructorArguments; 47 | if (ctorArgs.Length < 1) 48 | { 49 | context.ReportCorrectAttributeCtor(attribute, labelType); 50 | continue; 51 | } 52 | 53 | var label = ctorArgs[0]; 54 | if (!SymbolEqualityComparer.Default.Equals(label.Type, labelType)) 55 | { 56 | context.ReportCorrectAttributeCtor(attribute, labelType); 57 | continue; 58 | } 59 | 60 | string labelValue = label.ToDisplayValue(); 61 | 62 | yield return new AttributeItem 63 | { 64 | LabelType = labelType, 65 | InterfaceType = GetInterfaceType(productSymbol), 66 | ClassType = classSymbol, 67 | LabelValue = labelValue, 68 | Tags = GetTagsFromCtor(attribute).Concat(GetTagsFromProperty(attribute)).ToArray(), 69 | }; 70 | } 71 | } 72 | 73 | private static ITypeSymbol GetLabelType(INamedTypeSymbol symbol) 74 | { 75 | const int keyTypeIndex = 0; 76 | 77 | // e.g. ProductAttribute<*TKey*, TProduct>. 78 | return symbol.TypeArguments[keyTypeIndex]; 79 | } 80 | 81 | private static ITypeSymbol GetInterfaceType(INamedTypeSymbol symbol) 82 | { 83 | const int targetTypeIndex = 1; 84 | 85 | // e.g. ProductAttribute. 86 | return symbol.TypeArguments[targetTypeIndex]; 87 | } 88 | 89 | private static IEnumerable<(string key, string value)> GetTagsFromCtor(AttributeData attribute) 90 | { 91 | var parameters = attribute.AttributeConstructor!.Parameters; 92 | var arguments = attribute.ConstructorArguments; 93 | // skip the 'key' argument. 94 | foreach (var (x, y) in parameters.Zip(arguments, (x, y) => (x, y)).Skip(1)) 95 | { 96 | yield return (x.Name, y.ToDisplayValue()); 97 | } 98 | } 99 | 100 | private static IEnumerable<(string key, string value)> GetTagsFromProperty(AttributeData attribute) 101 | { 102 | var props = attribute.AttributeClass!.GetMembers().OfType().ToArray(); 103 | var propNames = props.Select(x => x.Name).ToArray(); 104 | var defaultValues = props 105 | .Select(x => (name: x.Name, value: GetDefaultValue(x))) 106 | .Where(x => !string.IsNullOrEmpty(x.value)) 107 | .ToDictionary(x => x.name, x => x.value!); 108 | var values = attribute.NamedArguments.ToDictionary(x => x.Key, x => x.Value.ToDisplayValue()); 109 | 110 | foreach (string propName in propNames) 111 | { 112 | if (values.TryGetValue(propName, out string value)) 113 | { 114 | yield return (propName, value); 115 | } 116 | else if (defaultValues.TryGetValue(propName, out value)) 117 | { 118 | yield return (propName, value); 119 | } 120 | else 121 | { 122 | yield return (propName, "default!"); 123 | } 124 | } 125 | 126 | static string? GetDefaultValue(IPropertySymbol property) 127 | { 128 | if (property.DeclaringSyntaxReferences.Length != 1) 129 | { 130 | return null; 131 | } 132 | 133 | if (property.DeclaringSyntaxReferences[0].GetSyntax() is not PropertyDeclarationSyntax syntax) 134 | { 135 | return null; 136 | } 137 | 138 | return syntax.Initializer is { } initializer 139 | ? GetDisplayValue(property.Type, initializer.Value) 140 | : null; 141 | } 142 | 143 | static string GetDisplayValue(ITypeSymbol type, ExpressionSyntax syntax) 144 | { 145 | return type switch 146 | { 147 | { TypeKind: TypeKind.Enum } => $"{type.ContainingSymbol.ToDeclaration()}.{syntax}", 148 | _ => syntax.ToString(), 149 | }; 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /SimpleFactoryGenerator/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | 7 | namespace SimpleFactoryGenerator; 8 | 9 | public static class Extensions 10 | { 11 | /// 12 | /// Creates all instances of the product in this simple-factory. 13 | /// 14 | /// The type of the feed used to produce products. 15 | /// The type of the product. 16 | /// The original factory instance. 17 | /// The arguments required by the constructor that creates this instance. 18 | /// Returns an iterable collection of products. 19 | public static IEnumerable CreateAll(this ISimpleFactory factory, params object?[] args) 20 | { 21 | foreach (var product in SimpleFactory.Products) 22 | { 23 | yield return factory.Create(product.Key, args); 24 | } 25 | } 26 | 27 | /// 28 | /// Determines if the specified instance can be used to create a product. 29 | /// 30 | /// The type of the feed used to produce products. 31 | /// The type of the product. 32 | /// The original factory instance. 33 | /// The specified instance. 34 | /// Returns a value to determine if the specified instance can be used to create a product. 35 | public static bool Contains(this ISimpleFactory factory, TKey key) 36 | { 37 | return SimpleFactory.Products.ContainsKey(key); 38 | } 39 | 40 | /// 41 | /// Try creates the product that match the specified key. 42 | /// 43 | /// The type of the feed used to produce products. 44 | /// The type of the product. 45 | /// The original factory instance. 46 | /// The specified instance. 47 | /// The product that match the specified key. 48 | /// The arguments required by the constructor that creates this instance. 49 | /// Returns a value to determine if it succeeded. 50 | public static bool TryCreate(this ISimpleFactory factory, TKey key, out TProduct product, params object?[] args) 51 | { 52 | if (factory.Contains(key)) 53 | { 54 | product = factory.Create(key, args); 55 | return true; 56 | } 57 | 58 | product = default!; 59 | return false; 60 | } 61 | 62 | /// 63 | /// Gets a wrapper of the instance, which will cache the created product instances. 64 | /// 65 | /// The type of the feed used to produce products. 66 | /// The type of the product. 67 | /// The original factory instance. 68 | /// The wrapped factory instance. 69 | public static ISimpleFactory WithCache(this ISimpleFactory factory) 70 | { 71 | ISimpleFactory originalFactory = factory is CacheSimpleFactory cacheFactory 72 | ? cacheFactory.Factory 73 | : factory; 74 | return new CacheSimpleFactory(originalFactory); 75 | } 76 | } 77 | 78 | sealed file class CacheSimpleFactory : ISimpleFactory 79 | { 80 | private readonly ConcurrentDictionary _cache = new(); 81 | 82 | public ISimpleFactory Factory { get; } 83 | 84 | public CacheSimpleFactory(ISimpleFactory factory) => Factory = factory; 85 | 86 | public ISimpleFactory WithCreator(ProductCreator creator) 87 | { 88 | _cache.Clear(); 89 | return Factory.WithCreator(creator); 90 | } 91 | 92 | public TProduct Create(TKey key, params object?[] args) 93 | { 94 | return _cache.GetOrAdd(new CacheKey(key, args), CreateInstance); 95 | 96 | TProduct CreateInstance(CacheKey x) => Factory.Create(x.Key, x.Args); 97 | } 98 | 99 | [DebuggerDisplay("{Key}")] 100 | private class CacheKey 101 | { 102 | public TKey Key { get; } 103 | 104 | public object?[] Args { get; } 105 | 106 | public CacheKey(TKey key, object?[] args) 107 | { 108 | Key = key; 109 | Args = args; 110 | } 111 | 112 | public override bool Equals(object obj) 113 | { 114 | var other = (CacheKey)obj; 115 | return EqualityComparer.Default.Equals(Key, other.Key) && 116 | Args.SequenceEqual(other.Args); 117 | } 118 | 119 | public override int GetHashCode() 120 | { 121 | int keyCode = Key?.GetHashCode() ?? 0; 122 | int argsCode = ((IStructuralEquatable)Args).GetHashCode(EqualityComparer.Default); 123 | 124 | unchecked 125 | { 126 | int hash = 17; 127 | hash = hash * 31 + keyCode; 128 | hash = hash * 31 + argsCode; 129 | return hash; 130 | } 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SimpleFactoryGenerator [![version](https://img.shields.io/nuget/v/SimpleFactoryGenerator.svg)](https://www.nuget.org/packages/SimpleFactoryGenerator) 2 | 3 | English | [中文](./README.zh-CN.md) 4 | 5 | This library is used to assist in the implementation of the *Simple Factory Pattern* by automatically generating conditional branch structure in the factory class at **compile time**, thus solving the problem of the pattern violating the ["open-close principle"](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle). 6 | 7 | ## 1. Why? 8 | 9 | The introduction and use of the *Simple Factory Pattern* will not be described here. One of the drawbacks of this pattern is the need to manually maintain a (potentially huge) conditional branch structure for creating concrete instances of a given enumeration type (including strings). As a result, the pattern violates the "open to extensions, closed to modifications" design principle, which is solved by this library. The idea is very simple: design principles are a set of rules of thumb to facilitate the maintenance of code by *Humans*, to compensate for some of the limitations of human thinking. Therefore, there is no violation of the *Design Principles* by simply leaving this difficult-to-maintain part of the code to the **compiler**. 10 | 11 | ## 2. How? 12 | 13 | Let's start by looking at a simple factory implemented in the traditional way, in order to facilitate comparison of the parts replaced by this library. 14 | 15 | ```csharp 16 | public interface IProduct 17 | { 18 | } 19 | 20 | public class Product1 : IProduct 21 | { 22 | } 23 | 24 | public class Product2 : IProduct 25 | { 26 | } 27 | 28 | public class SimpleFactory 29 | { 30 | public IProduct Create(string type) 31 | { 32 | // Here is the branch judgment that violates the open-close principle, 33 | // for example, when adding `Product3`, you need to manually add 34 | // a branch here (`"product_c" => new Product3(),`). 35 | return type switch 36 | { 37 | "product_a" => new Product1(), 38 | "product_b" => new Product2(), 39 | _ => throw new IndexOutOfRangeException(), 40 | } 41 | } 42 | } 43 | 44 | // Using 45 | 46 | var factory = new SimpleFactory(); 47 | IProduct product = factory.Create("product_a"); 48 | ``` 49 | 50 | After using this library, the writing of `SimpleFactory` will be omitted and instead, a `ProductAttribute` needs to be declared on the concrete `Product` type. You have already noticed: the Attribute uses generics, which requires [C# 11](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generics-and-attributes) support, for which you need to use Visual Studio 2022 and configure it in the `*.csproj` file: `preview`. 51 | 52 | > If your project cannot be configured for C# 11 or uses Visual Studio 2022, which prevents you from **directly** using Generic-Attribute, you can refer to section 3.1 and customize an Attribute to inherit from `ProductAttribute` (the Generic-Attribute definitions were allowed before C# 11, just not directly available). 53 | 54 | ```csharp 55 | // It can also be an abstract class, or a normal class, and it is not mandatory to be an interface. 56 | public interface IProduct 57 | { 58 | } 59 | 60 | [Product("product_a")] 61 | public class Product1 : IProduct 62 | { 63 | } 64 | 65 | [Product("product_b")] 66 | public class Product2 : IProduct 67 | { 68 | } 69 | 70 | // Using 71 | 72 | // The SimpleFactory static class are provided by this library. 73 | var factory = SimpleFactory 74 | .For() 75 | // .WithCache() is optional decorator 76 | // that caches created instances (i.e. instances with the same key are created multiple times 77 | // and the same instance is returned.) 78 | .WithCache(); 79 | IProduct product = factory.Create("product_a"); 80 | ``` 81 | 82 | ## 3. Advanced 83 | 84 | It's not really that advanced, it's such a simple requirement, what are you expecting? :) 85 | 86 | ### 3.1 Custom Attribute 87 | 88 | If you think the `ProductAttribute` declaration too long, too ugly, too cumbersome (or can't use C# 11's Generic-Attribute syntax), you can customize an Attribute to inherit it. 89 | 90 | ```csharp 91 | public class FruitAttribute : ProductAttribute 92 | { 93 | public FruitAttribute(string name) : base(name) 94 | { 95 | } 96 | } 97 | 98 | [Fruit("apple")] 99 | public class Apple : IProduct 100 | { 101 | } 102 | ``` 103 | 104 | ### 3.2 Mapping to multiple target interfaces 105 | 106 | For the same concrete product type, it is allowed to supply to multiple different target interfaces. 107 | 108 | ```csharp 109 | [Animal("mouse")] 110 | [Food("duck_neck")] 111 | public class Mouse : IAnimal, IFood 112 | { 113 | } 114 | 115 | // Using 116 | var animalFactory = SimpleFactory.For(); 117 | IProduct mouse = animalFactory.Create("mouse"); 118 | 119 | var foodFactory = SimpleFactory.For(); 120 | IProduct duckNeck = foodFactory.Create("duck_neck"); 121 | ``` 122 | 123 | ### 3.3 Passing arguments to the constructor 124 | 125 | If a constructor of type `Product` has parameters, they can be passed as follows: 126 | 127 | ```csharp 128 | _ = factory.Create("key", arg1, arg2, ...); 129 | ``` 130 | 131 | Since it is often not possible to determine the constructor that creates the type when using `factory`, it is recommended that all `Product` constructors have a consistent argument list. 132 | 133 | If there is a need to make the constructor arguments for each `Product` indeterminate, it is recommended that it be created in an Ioc container: 134 | 135 | ```csharp 136 | var factory = SimpleFactory 137 | .For() 138 | .WithCreator((type, args) => (Product)container.Resolve(type, args)); 139 | 140 | _ = factory.Create(key); 141 | ``` 142 | 143 | Note: If you use `.WithCreator()` after `.WithCache()`, it will cause the previous cache to be cleared. 144 | -------------------------------------------------------------------------------- /.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/main/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 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | .idea 400 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # To learn more about .editorconfig see https://aka.ms/editorconfigdocs 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Default settings: 7 | # A newline ending every file 8 | # Use 4 spaces as indentation 9 | [*] 10 | insert_final_newline = true 11 | indent_style = space 12 | indent_size = 4 13 | trim_trailing_whitespace = true 14 | 15 | [*.json] 16 | indent_size = 2 17 | 18 | [*.{cs,xaml}] 19 | charset = utf-8 20 | end_of_line = crlf 21 | 22 | # C# files 23 | [*.cs] 24 | # New line preferences 25 | csharp_new_line_before_open_brace = all 26 | csharp_new_line_before_else = true 27 | csharp_new_line_before_catch = true 28 | csharp_new_line_before_finally = true 29 | csharp_new_line_before_members_in_object_initializers = true 30 | csharp_new_line_before_members_in_anonymous_types = true 31 | csharp_new_line_between_query_expression_clauses = true 32 | 33 | # Indentation preferences 34 | csharp_indent_block_contents = true 35 | csharp_indent_braces = false 36 | csharp_indent_case_contents = true 37 | csharp_indent_case_contents_when_block = true 38 | csharp_indent_switch_labels = true 39 | csharp_indent_labels = one_less_than_current 40 | 41 | # Parentheses preferences 42 | dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary : silent 43 | dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary : silent 44 | dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary : silent 45 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary : silent 46 | 47 | # Modifier preferences 48 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async : suggestion 49 | dotnet_style_require_accessibility_modifiers = for_non_interface_members : warning 50 | 51 | # avoid this. unless absolutely necessary 52 | dotnet_style_qualification_for_field = false : suggestion 53 | dotnet_style_qualification_for_property = false : suggestion 54 | dotnet_style_qualification_for_method = false : suggestion 55 | dotnet_style_qualification_for_event = false : suggestion 56 | 57 | # Types: use keywords instead of BCL types, and permit var only when the type is clear 58 | csharp_style_var_for_built_in_types = false : suggestion 59 | csharp_style_var_when_type_is_apparent = false : none 60 | csharp_style_var_elsewhere = false : suggestion 61 | dotnet_style_predefined_type_for_locals_parameters_members = true : suggestion 62 | dotnet_style_predefined_type_for_member_access = true : suggestion 63 | 64 | # Naming Conventions 65 | 66 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 67 | 68 | dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case 69 | dotnet_naming_style.camel_case_underscore_style.required_prefix = _ 70 | 71 | dotnet_naming_style.interfaces_style.capitalization = pascal_case 72 | dotnet_naming_style.interfaces_style.required_prefix = I 73 | 74 | # name all constant fields using PascalCase 75 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion 76 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields 77 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style 78 | dotnet_naming_symbols.constant_fields.applicable_kinds = field 79 | dotnet_naming_symbols.constant_fields.required_modifiers = const 80 | 81 | # static fields using PascalCase 82 | dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion 83 | dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields 84 | dotnet_naming_rule.static_fields_should_have_prefix.style = pascal_case_style 85 | dotnet_naming_symbols.static_fields.applicable_kinds = field 86 | dotnet_naming_symbols.static_fields.required_modifiers = static 87 | dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected 88 | 89 | # internal and private fields should be _camelCase 90 | dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion 91 | dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields 92 | dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style 93 | dotnet_naming_symbols.private_internal_fields.applicable_kinds = field 94 | dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal 95 | 96 | # interfaces must have an I prefix 97 | dotnet_naming_rule.interfaces_must_be_interfaces_style.severity = suggestion 98 | dotnet_naming_rule.interfaces_must_be_interfaces_style.symbols = interfaces 99 | dotnet_naming_rule.interfaces_must_be_interfaces_style.style = interfaces_style 100 | dotnet_naming_symbols.interfaces.applicable_kinds = interface 101 | dotnet_naming_symbols.interfaces.applicable_accessibilities = * 102 | 103 | # Code style defaults 104 | csharp_using_directive_placement = outside_namespace : suggestion 105 | dotnet_sort_system_directives_first = true 106 | csharp_prefer_braces = true : suggestion 107 | csharp_preserve_single_line_blocks = true : none 108 | csharp_preserve_single_line_statements = false : none 109 | csharp_prefer_static_local_function = true : suggestion 110 | csharp_prefer_simple_using_statement = false : none 111 | csharp_style_prefer_switch_expression = true : suggestion 112 | 113 | # Code quality 114 | dotnet_style_readonly_field = true : suggestion 115 | dotnet_code_quality_unused_parameters = non_public : suggestion 116 | 117 | # Expression-level preferences 118 | dotnet_style_object_initializer = true : suggestion 119 | dotnet_style_collection_initializer = true : suggestion 120 | dotnet_style_explicit_tuple_names = true : suggestion 121 | dotnet_style_coalesce_expression = true : suggestion 122 | dotnet_style_null_propagation = true : suggestion 123 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true : suggestion 124 | dotnet_style_prefer_inferred_tuple_names = true : suggestion 125 | dotnet_style_prefer_inferred_anonymous_type_member_names = true : suggestion 126 | dotnet_style_prefer_auto_properties = true : suggestion 127 | dotnet_style_prefer_conditional_expression_over_assignment = true : refactoring 128 | dotnet_style_prefer_conditional_expression_over_return = true : refactoring 129 | csharp_prefer_simple_default_expression = true : suggestion 130 | csharp_style_deconstructed_variable_declaration = true : suggestion 131 | 132 | # Expression-bodied members 133 | csharp_style_expression_bodied_methods = true : refactoring 134 | csharp_style_expression_bodied_constructors = true : refactoring 135 | csharp_style_expression_bodied_operators = true : refactoring 136 | csharp_style_expression_bodied_properties = true : refactoring 137 | csharp_style_expression_bodied_indexers = true : refactoring 138 | csharp_style_expression_bodied_accessors = true : refactoring 139 | csharp_style_expression_bodied_lambdas = true : refactoring 140 | csharp_style_expression_bodied_local_functions = true : refactoring 141 | 142 | # Pattern matching 143 | csharp_style_pattern_matching_over_is_with_cast_check = true : suggestion 144 | csharp_style_pattern_matching_over_as_with_null_check = true : suggestion 145 | csharp_style_inlined_variable_declaration = true : suggestion 146 | 147 | # Null checking preferences 148 | csharp_style_throw_expression = true : suggestion 149 | csharp_style_conditional_delegate_call = true : suggestion 150 | 151 | # Other features 152 | csharp_style_prefer_index_operator = false : none 153 | csharp_style_prefer_range_operator = false : none 154 | csharp_style_pattern_local_over_anonymous_function = false : none 155 | 156 | # Space preferences 157 | csharp_space_after_cast = false 158 | csharp_space_after_colon_in_inheritance_clause = true 159 | csharp_space_after_comma = true 160 | csharp_space_after_dot = false 161 | csharp_space_after_keywords_in_control_flow_statements = true 162 | csharp_space_after_semicolon_in_for_statement = true 163 | csharp_space_around_binary_operators = before_and_after 164 | csharp_space_around_declaration_statements = do_not_ignore 165 | csharp_space_before_colon_in_inheritance_clause = true 166 | csharp_space_before_comma = false 167 | csharp_space_before_dot = false 168 | csharp_space_before_open_square_brackets = false 169 | csharp_space_before_semicolon_in_for_statement = false 170 | csharp_space_between_empty_square_brackets = false 171 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 172 | csharp_space_between_method_call_name_and_opening_parenthesis = false 173 | csharp_space_between_method_call_parameter_list_parentheses = false 174 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 175 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 176 | csharp_space_between_method_declaration_parameter_list_parentheses = false 177 | csharp_space_between_parentheses = false 178 | csharp_space_between_square_brackets = false 179 | 180 | # Analyzers 181 | dotnet_code_quality.ca1802.api_surface = private, internal 182 | 183 | # C++ Files 184 | [*.{cpp,h,in}] 185 | curly_bracket_next_line = true 186 | indent_brace_style = Allman 187 | 188 | # Xml project files 189 | [*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] 190 | indent_size = 2 191 | 192 | # Xml build files 193 | [*.builds] 194 | indent_size = 2 195 | 196 | # Xml files 197 | [*.{xml,stylecop,resx,ruleset}] 198 | indent_size = 2 199 | 200 | # Xml config files 201 | [*.{props,targets,config,nuspec}] 202 | indent_size = 2 203 | 204 | # Shell scripts 205 | [*.sh] 206 | end_of_line = lf 207 | [*.{cmd, bat}] 208 | end_of_line = crlf 209 | --------------------------------------------------------------------------------