AutoImplementation.CodeGeneration 1.0.3

dotnet add package AutoImplementation.CodeGeneration --version 1.0.3
                    
NuGet\Install-Package AutoImplementation.CodeGeneration -Version 1.0.3
                    
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="AutoImplementation.CodeGeneration" Version="1.0.3">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AutoImplementation.CodeGeneration" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="AutoImplementation.CodeGeneration">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AutoImplementation.CodeGeneration --version 1.0.3
                    
#r "nuget: AutoImplementation.CodeGeneration, 1.0.3"
                    
#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.
#:package AutoImplementation.CodeGeneration@1.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AutoImplementation.CodeGeneration&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=AutoImplementation.CodeGeneration&version=1.0.3
                    
Install as a Cake Tool

AutoImplementation.CodeGeneration

Source Generator que cria automaticamente implementações conc### ✅ Propriedades

  • Propriedades get-only são geradas com init
  • Propriedades de tipos não-nullable são geradas com required
  • Propriedades de tipos nullable (string?, int?, etc.) não são required
  • Suporte completo a tipos complexos e genéricos
  • Using statements da interface são automaticamente incluídos no código gerado (records/classes) para interfaces anotadas com o atributo GenerateImplementationAttribute.

Como usar

1. Anote sua interface

Use o atributo [GenerateImplementation] em interfaces para gerar automaticamente uma implementação concreta:

using AutoImplementation.CodeGeneration;

[GenerateImplementation]
public interface IPerson
{
    string Name { get; }
    int Age { get; }
    string Email { get; }
}

2. Código gerado automaticamente

O Source Generator criará automaticamente uma implementação:

// <auto-generated/>
public partial record Person : IPerson
{
    public required string Name { get; init; }
    public required int Age { get; init; }
    public required string Email { get; init; }
}

3. Use a implementação gerada

var person = new Person 
{ 
    Name = "João", 
    Age = 30, 
    Email = "joao@example.com" 
};

Opções do atributo

O atributo GenerateImplementationAttribute aceita dois parâmetros opcionais:

Parâmetro className

Define o nome da classe/record gerada. Se não especificado, remove o prefixo 'I' do nome da interface:

[GenerateImplementation("Customer")]
public interface IUser
{
    string Name { get; }
}

// Gera: public partial record Customer : IUser

Parâmetro useRecord

Define se deve gerar um record (padrão: true) ou uma class (quando false):

[GenerateImplementation(useRecord: false)]
public interface IPerson
{
    string Name { get; }
    int Age { get; }
}

// Gera uma class com propriedades required:
public partial class Person : IPerson
{
    public required string Name { get; init; }
    public required int Age { get; init; }
}

Combinando ambos os parâmetros

[GenerateImplementation("Employee", useRecord: false)]
public interface IPerson
{
    string Name { get; }
    string Department { get; }
}

// Gera: public partial class Employee : IPerson

Recursos suportados

✅ Propriedades

  • Propriedades get-only são geradas com init
  • Propriedades de tipos não-nullable são geradas com required
  • Propriedades de tipos nullable (string?, int?, etc.) não são required
  • Suporte completo a tipos complexos e genéricos
  • Resolução automática de referências: tipos com referência completa (como List<Shared.DataTransfer.PurchaseOrder.ProductItem>) são resolvidos automaticamente com os using statements apropriados

✅ Herança de Interfaces

  • Suporte completo a interfaces que herdam de outras interfaces
  • Todos os membros (propriedades, métodos, eventos) das interfaces base são automaticamente incluídos
  • Funciona com herança múltipla e hierarquias complexas
  • Prevenção automática de duplicatas em casos de herança diamante
  • Veja documentação detalhada

✅ Métodos

  • Métodos são gerados com throw new NotImplementedException()
  • Suporte a parâmetros ref, out, in
  • Suporte a valores padrão de parâmetros

✅ Eventos

  • Eventos são gerados como propriedades de evento padrão

⚠️ Indexers

  • Indexers são suportados mas geram NotImplementedException
  • Um diagnóstico informativo é emitido para indexers

Exemplos avançados

Interface com métodos

[GenerateImplementation]
public interface ICalculator
{
    double Result { get; }
    void Add(double value);
    void Subtract(double value);
    void Clear();
}

// Gera um record com propriedades required e métodos com NotImplementedException

Interface com eventos

[GenerateImplementation]
public interface INotifier
{
    string Message { get; }
    event Action<string> OnNotification;
    void Notify(string message);
}

Interface genérica

[GenerateImplementation]
public interface IRepository<T>
{
    IEnumerable<T> Items { get; }
    void Add(T item);
    T? GetById(int id);
}

// Gera: public partial record Repository<T> : IRepository<T>

Interface com tipos nullable

[GenerateImplementation]
public interface IUser
{
    string Name { get; }        // required (não-nullable)
    string? Email { get; }      // não é required (nullable)
    int Age { get; }            // required (não-nullable)
    int? Score { get; }         // não é required (nullable)
}

// Gera:
public partial record User : IUser
{
    public required string Name { get; init; }
    public string? Email { get; init; }         // sem required
    public required int Age { get; init; }
    public int? Score { get; init; }            // sem required
}

Interface com herança

// Interface base
public interface IEntity
{
    int Id { get; }
    DateTime CreatedAt { get; }
}

// Interface derivada
[GenerateImplementation]
public interface IProduct : IEntity
{
    string Name { get; }
    decimal Price { get; }
}

// Gera um record com TODAS as propriedades:
public partial record Product : IProduct
{
    public required int Id { get; init; }              // de IEntity
    public required DateTime CreatedAt { get; init; }  // de IEntity
    public required string Name { get; init; }         // de IProduct
    public required decimal Price { get; init; }       // de IProduct
}

Interface com herança múltipla

public interface IEntity
{
    int Id { get; }
}

public interface IAuditable
{
    DateTime CreatedAt { get; }
    DateTime? UpdatedAt { get; }
}

[GenerateImplementation]
public interface IProduct : IEntity, IAuditable
{
    string Name { get; }
    decimal Price { get; }
}

// Gera um record com propriedades de TODAS as interfaces:
public partial record Product : IProduct
{
    public required int Id { get; init; }              // de IEntity
    public required DateTime CreatedAt { get; init; }  // de IAuditable
    public DateTime? UpdatedAt { get; init; }          // de IAuditable
    public required string Name { get; init; }         // de IProduct
    public required decimal Price { get; init; }       // de IProduct
}

Interface com referências completas

namespace MyProject.Orders;

[GenerateImplementation]
public interface IPurchaseOrder
{
    List<Shared.DataTransfer.PurchaseOrder.ProductItem> Items { get; }
    Shared.Common.Address DeliveryAddress { get; }
    System.Collections.Generic.Dictionary<string, object> Metadata { get; }
}

// Gera automaticamente:
using Shared.DataTransfer.PurchaseOrder;
using Shared.Common;

namespace MyProject.Orders
{
    public partial record PurchaseOrder : IPurchaseOrder
    {
        public required List<ProductItem> Items { get; init; }
        public required Address DeliveryAddress { get; init; }
        public required Dictionary<string, object> Metadata { get; init; }
    }
}

Interface com dependências externas

using System.Collections.Generic;
using System.Threading.Tasks;
using MyProject.Models;

[GenerateImplementation]
public interface IDataService
{
    List<Customer> Customers { get; }
    Task<bool> SaveAsync(Customer customer);
}

// Gera (com using statements incluídos):
using System.Collections.Generic;
using System.Threading.Tasks;
using MyProject.Models;

public partial record DataService : IDataService
{
    public required List<Customer> Customers { get; init; }
    
    public Task<bool> SaveAsync(Customer customer)
    {
        throw new System.NotImplementedException();
    }
}

Notas importantes

  • As implementações geradas são parciais, permitindo extensão manual
  • Propriedades não-nullable são geradas com required para garantir inicialização
  • Propriedades nullable não são required, permitindo valores nulos opcionais
  • Use object initializers para instanciar os tipos gerados
  • Métodos sempre lançam NotImplementedException e devem ser implementados manualmente se necessário

Diagnósticos

O Source Generator emite diagnósticos informativos:

  • GI0001: Informa quando indexers são encontrados em interfaces (eles são gerados com NotImplementedException)

Compatibilidade

  • .NET Standard 2.0+
  • C# 9.0+ (para suporte a records e propriedades required)
  • Funciona com qualquer projeto que suporte Source Generators
There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

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
1.0.3 363 10/23/2025
1.0.2 194 9/30/2025
1.0.1 186 9/30/2025
1.0.0 191 9/30/2025