SimpleFactoryGenerator 0.8.0

Requires NuGet 2.12 or higher.

dotnet add package SimpleFactoryGenerator --version 0.8.0
NuGet\Install-Package SimpleFactoryGenerator -Version 0.8.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SimpleFactoryGenerator" Version="0.8.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SimpleFactoryGenerator --version 0.8.0
#r "nuget: SimpleFactoryGenerator, 0.8.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install SimpleFactoryGenerator as a Cake Addin
#addin nuget:?package=SimpleFactoryGenerator&version=0.8.0

// Install SimpleFactoryGenerator as a Cake Tool
#tool nuget:?package=SimpleFactoryGenerator&version=0.8.0

SimpleFactoryGenerator version

English | δΈ­ζ–‡

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".

1. Why?

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.

2. How?

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.

public interface IProduct
{
}

public class Product1 : IProduct
{
}

public class Product2 : IProduct
{
}

public class SimpleFactory
{
    public IProduct Create(string type)
    {
        // Here is the branch judgment that violates the open-close principle,
        // for example, when adding `Product3`, you need to manually add
        // a branch here (`"product_c" => new Product3(),`).
        return type switch
        {
            "product_a" => new Product1(),
            "product_b" => new Product2(),
            _ => throw new IndexOutOfRangeException(),
        }
    }
}

// Using

var factory = new SimpleFactory();
IProduct product = factory.Create("product_a");

After using this library, the writing of SimpleFactory will be omitted and instead, a ProductAttribute<K, T> needs to be declared on the concrete Product type. You have already noticed: the Attribute uses generics, which requires C# 11 support, for which you need to use Visual Studio 2022 and configure it in the *.csproj file: <LangVersion>preview</LangVersion>.

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<K, T> (the Generic-Attribute definitions were allowed before C# 11, just not directly available).

// It can also be an abstract class, or a normal class, and it is not mandatory to be an interface.
public interface IProduct
{
}

[Product<string, IProduct>("product_a")]
public class Product1 : IProduct
{
}

[Product<string, IProduct>("product_b")]
public class Product2 : IProduct
{
}

// Using

// The SimpleFactory static class are provided by this library.
var factory = SimpleFactory
    .For<string, IProduct>()
    // .WithCache() is optional and when used will help implement the *Flyweight Pattern*
    // that caches created instances (i.e. instances with the same key are created multiple times
    // and the same instance is returned.)
    .WithCache();
IProduct product = factory.Create("product_a");

3. Advanced

It's not really that advanced, it's such a simple requirement, what are you expecting? πŸ˜ƒ

3.1 Custom Attribute

If you think the ProductAttribute<K, T> 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.

public class FruitAttribute : ProductAttribute<string, IProduct>
{
    public FruitAttribute(string name) : base(name)
    {
    }
}

[Fruit("apple")]
public class Apple : IProduct
{
}

3.2 Mapping to multiple target interfaces

For the same concrete product type, it is allowed to supply to multiple different target interfaces.

[Animal("mouse")]
[Food("duck_neck")]
public class Mouse : IAnimal, IFood
{
}

// Using
var animalFactory = SimpleFactory.For<string, IAnimal>();
IProduct mouse = animalFactory.Create("mouse");

var foodFactory = SimpleFactory.For<string, IFood>();
IProduct duckNeck = foodFactory.Create("duck_neck");

3.3 Passing arguments to the constructor

If a constructor of type Product has parameters, they can be passed as follows:

_ = factory.Create("key", arg1, arg2, ...);

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.

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:

var factory = SimpleFactory
    .For<Key, Product>()
    .WithCreator((type, args) => (Product)container.Resolve(type, args));

_ = factory.Create(key);

Note: If you use .WithCreator() after .WithCache(), it will cause the previous cache to be cleared.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.8.0 138 9/18/2023
0.7.5 137 8/10/2023