.NET source generator that automatically generates and registers factories
Add the following packages to your project:
$ dotnet add package FactoryGenerator.Abstractions
$ dotnet add package FactoryGenerator.Microsoft.Extensions.DependencyInjection
Use one of the GenerateIFactory
attributes to specify how your factory should be
generated:
[GenerateIFactory<int>]
public class Service(int value, Dependency dependency)
{
// ...
}
This will generate an implementation of IFactory<int, Service>
, allowing you to create instances of Service
with an
int
parameter while automatically resolving other dependencies from the DI container. FactoryGenerator
provides multiple attribute variations
depending on the number of parameters your factory should accept.
The RegisterGeneratedFactories()
method automatically registers all factories created by the source
generator.
var serviceCollection = new ServiceCollection()
.RegisterGeneratedFactories();
using var serviceProvider = serviceCollection.BuildServiceProvider();
var factory = serviceProvider.GetRequiredService<IFactory<int, Service>>();
var service = factory.Create(1);
Full sample can be found here.