AutoImplementation.CodeGeneration
1.0.3
dotnet add package AutoImplementation.CodeGeneration --version 1.0.3
NuGet\Install-Package AutoImplementation.CodeGeneration -Version 1.0.3
<PackageReference Include="AutoImplementation.CodeGeneration" Version="1.0.3"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="AutoImplementation.CodeGeneration" Version="1.0.3" />
<PackageReference Include="AutoImplementation.CodeGeneration"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add AutoImplementation.CodeGeneration --version 1.0.3
#r "nuget: AutoImplementation.CodeGeneration, 1.0.3"
#:package AutoImplementation.CodeGeneration@1.0.3
#addin nuget:?package=AutoImplementation.CodeGeneration&version=1.0.3
#tool nuget:?package=AutoImplementation.CodeGeneration&version=1.0.3
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ãorequired - 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ãorequired - 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 osusingstatements 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
requiredpara 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
NotImplementedExceptione 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
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- Microsoft.CodeAnalysis.Common (>= 4.14.0)
- Microsoft.CodeAnalysis.CSharp (>= 4.14.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.