Skip to content

Attribute API Reference

davidkallesen edited this page Mar 12, 2026 · 1 revision

Attribute API Reference

This page documents all public attributes, enums, and configuration types provided by Atc.SourceGenerators.Annotations. These are the compile-time annotations that drive the source generators.

Package: Atc.SourceGenerators.Annotations


Table of Contents


Dependency Registration

RegistrationAttribute

Marks a class for automatic registration in the dependency injection container.

Namespace Atc.DependencyInjection
Target Class
AllowMultiple false
Inherited false

Constructor Parameters

Parameter Type Default Description
lifetime Lifetime Lifetime.Singleton The service lifetime for the registration.

Named Properties

Property Type Default Description
As Type? null The service type to register against (typically an interface or abstract class). If not specified, the service is registered as its concrete type.
AsSelf bool false When true and As is specified, registers the service both as the interface and as its concrete type.
Decorator bool false When true, this service wraps the previous registration of the same interface. The decorator's constructor must accept the decorated interface as the first parameter.
Instance string? null Name of a static field, property, or parameterless method that provides a pre-created instance. Requires Singleton lifetime. Mutually exclusive with Factory.
Condition string? null Configuration key path that determines whether this service should be registered. The service is registered only if the configuration value evaluates to true. Prefix with ! to negate.

Usage Example

using Atc.DependencyInjection;

// Basic singleton registration (auto-detects interfaces)
[Registration]
public class UserService : IUserService { }

// Scoped registration against a specific interface
[Registration(Lifetime.Scoped, As = typeof(IOrderService))]
public class OrderService : IOrderService { }

// Decorator pattern
[Registration(Lifetime.Scoped, As = typeof(IOrderService), Decorator = true)]
public class LoggingOrderServiceDecorator : IOrderService { }

// Conditional registration based on configuration
[Registration(As = typeof(ICache), Condition = "Features:UseRedisCache")]
public class RedisCache : ICache { }

// Instance registration
[Registration(As = typeof(IAppConfig), Instance = nameof(Default))]
public class AppConfig : IAppConfig
{
    public static readonly AppConfig Default = new();
}

See Working with Dependency Registration for full documentation.


RegistrationFilterAttribute

Excludes types from automatic registration during assembly scanning. This attribute is defined as a fallback attribute inside the generator (not in the Annotations package) and is applied at the assembly level.

Namespace Atc.DependencyInjection
Target Assembly
AllowMultiple true
Inherited false

Named Properties

Property Type Default Description
ExcludeNamespaces string[]? null Namespaces to exclude from registration. Types in these namespaces (or sub-namespaces) will not be registered.
ExcludePatterns string[]? null Naming patterns to exclude. Supports wildcards: * matches any characters, ? matches a single character.
ExcludeImplementing Type[]? null Interface types to exclude. Types implementing any of these interfaces will not be registered.

Usage Example

using Atc.DependencyInjection;

[assembly: RegistrationFilter(ExcludeNamespaces = new[] { "MyApp.Internal", "MyApp.Tests" })]
[assembly: RegistrationFilter(ExcludePatterns = new[] { "*Mock*", "*Test*" })]
[assembly: RegistrationFilter(ExcludeImplementing = new[] { typeof(ITestUtility) })]

See Working with Dependency Registration for full documentation.


Lifetime (enum)

Service lifetime enum matching Microsoft.Extensions.DependencyInjection.ServiceLifetime.

Namespace Atc.DependencyInjection
Value Integer Description
Singleton 0 A single instance is created and shared for the application lifetime. This is the default.
Scoped 1 A new instance is created for each scope (e.g., each HTTP request).
Transient 2 A new instance is created every time the service is requested.

Options Binding

OptionsBindingAttribute

Marks a class for automatic options binding from configuration. The decorated class must be declared partial.

Namespace Atc.SourceGenerators.Annotations
Target Class
AllowMultiple true
Inherited false

Constructor Parameters

Parameter Type Default Description
sectionName string? null The configuration section name. If null, resolved by priority: (1) const string SectionName, (2) const string NameTitle, (3) const string Name, (4) auto-inferred from class name.

Named Properties

Property Type Default Description
ValidateOnStart bool false Validate the options on application start.
ValidateDataAnnotations bool false Validate using data annotations ([Required], [StringLength], etc.).
Lifetime OptionsLifetime Singleton The options lifetime (Singleton, Scoped, or Monitor).
Validator Type? null Custom validator type. Must implement IValidateOptions<T>. Registered as a singleton.
Name string? null Name for named options instances. Use IOptionsSnapshot<T>.Get(name) to retrieve.
ErrorOnMissingKeys bool false Throw an exception if the configuration section is missing or empty. Recommended to combine with ValidateOnStart = true.
OnChange string? null Name of a static method to call when configuration changes. Requires Lifetime = OptionsLifetime.Monitor. Method signature: static void MethodName(TOptions options, string? name).
PostConfigure string? null Name of a static method to call after binding and validation. Method signature: static void MethodName(TOptions options). Cannot be used with named options.
ConfigureAll string? null Name of a static method to configure all named instances with default values. Method signature: static void MethodName(TOptions options). Only applicable with multiple named instances.
ChildSections string[]? null Array of child section names to bind under the parent section. Creates multiple named instances. Mutually exclusive with Name. Requires at least 2 items.
AlsoRegisterDirectType bool false Also register the options type as a direct service (not wrapped in IOptions<T>). Useful for migration scenarios and third-party library compatibility.

Usage Example

using Atc.SourceGenerators.Annotations;

// Basic options binding with validation
[OptionsBinding("Database", ValidateDataAnnotations = true, ValidateOnStart = true)]
public partial class DatabaseOptions
{
    [Required]
    public string ConnectionString { get; set; } = string.Empty;
}

// Named options with child sections
[OptionsBinding("Email", ChildSections = new[] { "Primary", "Secondary" },
    ConfigureAll = nameof(SetDefaults))]
public partial class EmailOptions
{
    public string SmtpServer { get; set; } = string.Empty;
    internal static void SetDefaults(EmailOptions options) { options.SmtpServer = "localhost"; }
}

// Monitor lifetime with change notifications
[OptionsBinding("Features", Lifetime = OptionsLifetime.Monitor, OnChange = nameof(OnChanged))]
public partial class FeaturesOptions
{
    public bool EnableNewUI { get; set; }
    internal static void OnChanged(FeaturesOptions options, string? name) { }
}

See Working with Options Binding for full documentation.


OptionsLifetime (enum)

Options lifetime enum for configuration options binding.

Namespace Atc.SourceGenerators.Annotations
Value Integer Description
Singleton 0 Resolved using IOptions<T>. Computed once and cached for the application lifetime. This is the default.
Scoped 1 Resolved using IOptionsSnapshot<T>. Computed once per request/scope; supports reloadable configuration.
Monitor 2 Resolved using IOptionsMonitor<T>. Supports change notifications and is recomputed when configuration changes.

Object Mapping

MapToAttribute

Marks a class or enum for automatic mapping code generation. Generates extension methods to map from the decorated type to the specified target type. Classes must be declared partial; enums do not need to be partial.

Namespace Atc.SourceGenerators.Annotations
Target Class, Enum
AllowMultiple true
Inherited false

Constructor Parameters

Parameter Type Default Description
targetType Type (required) The target type to map to.

Named Properties

Property Type Default Description
Bidirectional bool false Generate both forward (Source -> Target) and reverse (Target -> Source) mappings.
EnableFlattening bool false Enable property flattening. Nested properties are flattened using {PropertyName}{NestedPropertyName} convention (e.g., source.Address.City maps to target.AddressCity).
BeforeMap string? null Name of a static method to call before mapping. Signature: static void MethodName(SourceType source).
AfterMap string? null Name of a static method to call after mapping. Signature: static void MethodName(SourceType source, TargetType target).
Factory string? null Name of a static factory method to create the target instance. Signature: static TargetType MethodName().
UpdateTarget bool false Generate an additional method overload that updates an existing target instance instead of creating a new one. Generates both MapToX() and MapToX(target).
GenerateProjection bool false Generate an Expression<Func<TSource, TTarget>> projection method for use with IQueryable (EF Core). Limitations: no hooks, no factory, no nested object mappings.
IncludePrivateMembers bool false Include private and internal members in the mapping using UnsafeAccessor (.NET 8+). Fully AOT compatible.
PropertyNameStrategy PropertyNameStrategy PascalCase Naming strategy for property name conversion (PascalCase, camelCase, snake_case, kebab-case). Explicit [MapProperty] mappings always take precedence.

Usage Example

using Atc.SourceGenerators.Annotations;

// Basic class mapping
[MapTo(typeof(UserDto))]
public partial class User
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

// Bidirectional enum mapping
[MapTo(typeof(StatusDto), Bidirectional = true)]
public enum Status { None, Active, Inactive }

// Advanced mapping with hooks and projection
[MapTo(typeof(OrderDto), BeforeMap = nameof(Validate), AfterMap = nameof(Enrich),
    GenerateProjection = true, UpdateTarget = true)]
public partial class Order
{
    public Guid Id { get; set; }
    private static void Validate(Order source) { }
    private static void Enrich(Order source, OrderDto target) { }
}

See Working with Object Mapping for class mapping and Working with Enum Mapping for enum mapping.


MapPropertyAttribute

Specifies a custom target property name for mapping when property names differ between source and target types.

Namespace Atc.SourceGenerators.Annotations
Target Property
AllowMultiple false
Inherited false

Constructor Parameters

Parameter Type Default Description
targetPropertyName string (required) The name of the target property to map to. Can use nameof() for type safety.

Named Properties

None.

Usage Example

[MapTo(typeof(UserDto))]
public partial class User
{
    public Guid Id { get; set; }

    [MapProperty(nameof(UserDto.FullName))]
    public string Name { get; set; } = string.Empty;

    [MapProperty("Age")]
    public int YearsOld { get; set; }
}

See Working with Object Mapping for full documentation.


MapIgnoreAttribute

Marks a property to be excluded from automatic mapping. Can be applied to properties on either the source or target type.

Namespace Atc.SourceGenerators.Annotations
Target Property
AllowMultiple false
Inherited false

Constructor Parameters

None.

Named Properties

None.

Usage Example

[MapTo(typeof(UserDto))]
public partial class User
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;

    [MapIgnore]
    public byte[] PasswordHash { get; set; } = Array.Empty<byte>();

    [MapIgnore]
    public DateTime CreatedAt { get; set; }
}

See Working with Object Mapping for full documentation.


MapDerivedTypeAttribute

Specifies a derived type mapping for polymorphic object mapping. Used on abstract base classes or interfaces in conjunction with [MapTo] to define how each derived type should be mapped. The generator creates a switch expression with runtime type pattern matching.

Namespace Atc.SourceGenerators.Annotations
Target Class
AllowMultiple true
Inherited false

Constructor Parameters

Parameter Type Default Description
sourceType Type (required) The source derived type to match during polymorphic mapping.
targetType Type (required) The target derived type to map to when the source type matches.

Named Properties

None.

Usage Example

// Base class with polymorphic mapping
[MapTo(typeof(Animal))]
[MapDerivedType(typeof(DogEntity), typeof(Dog))]
[MapDerivedType(typeof(CatEntity), typeof(Cat))]
public abstract partial class AnimalEntity { }

// Each derived type needs its own [MapTo]
[MapTo(typeof(Dog))]
public partial class DogEntity : AnimalEntity
{
    public string Breed { get; set; } = "";
}

[MapTo(typeof(Cat))]
public partial class CatEntity : AnimalEntity
{
    public int Lives { get; set; }
}

// Generated method dispatches by runtime type:
// animalEntity.MapToAnimal() performs type switching internally

See Working with Object Mapping for full documentation.


PropertyNameStrategy (enum)

Defines strategies for converting property names during mapping. Used to map between different naming conventions.

Namespace Atc.SourceGenerators.Annotations
Value Integer Description Example
PascalCase 0 No transformation. Names must match exactly (case-insensitive). This is the default. FirstName matches FirstName
CamelCase 1 Convert PascalCase source properties to camelCase for matching. FirstName matches firstName
SnakeCase 2 Convert PascalCase source properties to snake_case for matching. FirstName matches first_name
KebabCase 3 Convert PascalCase source properties to kebab-case for matching. FirstName matches first-name

Configuration-Based Mapping

These attributes are used for mapping third-party types from external assemblies where you cannot add [MapTo] attributes to the source types.

MappingConfigurationAttribute

Marks a static partial class as a mapping configuration container. Methods in this class define mapping operations for external types.

Namespace Atc.SourceGenerators.Annotations
Target Class
AllowMultiple false
Inherited false

Constructor Parameters

None.

Named Properties

None.

Requirements

  • The decorated class must be static and partial.
  • Each method must be a partial extension method (first parameter uses this keyword).
  • The return type is the target type; the extension method parameter type is the source type.

Usage Example

[MappingConfiguration]
public static partial class ExternalMappings
{
    public static partial CustomerDto MapToCustomerDto(this ThirdParty.Contact source);

    [MapConfigIgnore("InternalId")]
    [MapConfigProperty("FullName", "DisplayName")]
    public static partial UserDto MapToUserDto(this ThirdParty.User source);
}

See Configuration Based Mapping for full documentation.


MapConfigPropertyAttribute

Specifies a property name mapping between source and target types in configuration-based mapping. Applied to partial methods in a [MappingConfiguration] class.

Namespace Atc.SourceGenerators.Annotations
Target Method
AllowMultiple true
Inherited false

Constructor Parameters

Parameter Type Default Description
sourcePropertyName string (required) The name of the property on the source type.
targetPropertyName string (required) The name of the property on the target type.

Named Properties

None.

Usage Example

[MappingConfiguration]
public static partial class ExternalMappings
{
    [MapConfigProperty("FullName", "DisplayName")]
    [MapConfigProperty("EmailAddress", "Email")]
    public static partial CustomerDto MapToCustomerDto(this ThirdParty.Contact source);
}

See Configuration Based Mapping for full documentation.


MapConfigIgnoreAttribute

Specifies a source property to exclude from configuration-based mapping. Applied to partial methods in a [MappingConfiguration] class.

Namespace Atc.SourceGenerators.Annotations
Target Method
AllowMultiple true
Inherited false

Constructor Parameters

Parameter Type Default Description
propertyName string (required) The name of the source property to exclude from mapping.

Named Properties

None.

Usage Example

[MappingConfiguration]
public static partial class ExternalMappings
{
    [MapConfigIgnore("InternalId")]
    [MapConfigIgnore("PasswordHash")]
    public static partial UserDto MapToUserDto(this ThirdParty.User source);
}

See Configuration Based Mapping for full documentation.


MapConfigOptionsAttribute

Configures advanced mapping options for a configuration-based mapping method. Applied to partial methods in a [MappingConfiguration] class. This attribute is optional; when omitted, default mapping behavior is used.

Namespace Atc.SourceGenerators.Annotations
Target Method
AllowMultiple false
Inherited false

Constructor Parameters

None.

Named Properties

Property Type Default Description
Bidirectional bool false Generate both forward and reverse mappings.
EnableFlattening bool false Enable property flattening using {PropertyName}{NestedPropertyName} convention.
PropertyNameStrategy PropertyNameStrategy PascalCase Naming strategy for property name conversion during mapping.

Usage Example

[MappingConfiguration]
public static partial class ExternalMappings
{
    [MapConfigOptions(Bidirectional = true, PropertyNameStrategy = PropertyNameStrategy.SnakeCase)]
    public static partial OrderDto MapToOrderDto(this ExternalLib.Order source);
}

See Configuration Based Mapping for full documentation.


MapTypesAttribute

Defines a mapping between two types at the assembly level. This is a shorthand alternative to [MappingConfiguration] for simple mapping scenarios that do not require per-method configuration.

Namespace Atc.SourceGenerators.Annotations
Target Assembly, Class
AllowMultiple true
Inherited default

Constructor Parameters

Parameter Type Default Description
sourceType Type (required) The source type to map from.
targetType Type (required) The target type to map to.

Named Properties

Property Type Default Description
PropertyMap string[]? null Property name mappings in "SourceProperty:TargetProperty" format.
IgnoreSourceProperties string[]? null Source property names to exclude from mapping.
IgnoreTargetProperties string[]? null Target property names to exclude from mapping.
Bidirectional bool false Generate bidirectional mappings.
PropertyNameStrategy PropertyNameStrategy PascalCase Naming strategy for property name conversion.

Usage Example

// Assembly-level shorthand
[assembly: MapTypes(typeof(ExternalLib.Contact), typeof(MyApp.Customer),
    PropertyMap = new[] { "EmailAddress:Email", "PhoneNumber:Phone" },
    IgnoreSourceProperties = new[] { "InternalId" },
    Bidirectional = true)]

See Configuration Based Mapping for full documentation.


MappingBuilder

A fluent API class for configuring type mappings inline. The Map() calls are analyzed at compile time by the source generator to produce mapping extension methods. At runtime, this class is a no-op.

Namespace Atc.SourceGenerators.Annotations
Type sealed class

Static Methods

Method Description
Configure(Action<MappingBuilder> configure) Entry point for configuring mappings. The lambda body is analyzed at compile time. At runtime, this is a no-op.

Instance Methods

Map(Type sourceType, Type targetType, ...) -- Registers a mapping between two types using typeof() expressions.

Parameter Type Default Description
sourceType Type (required) The source type to map from.
targetType Type (required) The target type to map to.
bidirectional bool false Whether to generate bidirectional mappings.
propertyMap string[]? null Property name mappings in "SourceProperty:TargetProperty" format.
ignoreSourceProperties string[]? null Source property names to exclude.
ignoreTargetProperties string[]? null Target property names to exclude.
propertyNameStrategy PropertyNameStrategy PascalCase Naming strategy for property name conversion.

Map<TSource, TTarget>(...) -- Generic overload. Same parameters as above (excluding sourceType and targetType), using type parameters instead.

Usage Example

MappingBuilder.Configure(builder => builder
    .Map<ExternalLib.Contact, MyApp.Customer>(
        bidirectional: true,
        propertyMap: new[] { "EmailAddress:Email" },
        ignoreSourceProperties: new[] { "InternalId" })
    .Map<ExternalLib.Order, MyApp.OrderDto>());

See Configuration Based Mapping for full documentation.


Quick Reference Table

Attribute Target Generator Namespace
[Registration] Class DependencyRegistration Atc.DependencyInjection
[RegistrationFilter] Assembly DependencyRegistration Atc.DependencyInjection
[OptionsBinding] Class OptionsBinding Atc.SourceGenerators.Annotations
[MapTo] Class, Enum ObjectMapping / EnumMapping Atc.SourceGenerators.Annotations
[MapProperty] Property ObjectMapping Atc.SourceGenerators.Annotations
[MapIgnore] Property ObjectMapping Atc.SourceGenerators.Annotations
[MapDerivedType] Class ObjectMapping Atc.SourceGenerators.Annotations
[MappingConfiguration] Class MappingConfiguration Atc.SourceGenerators.Annotations
[MapConfigProperty] Method MappingConfiguration Atc.SourceGenerators.Annotations
[MapConfigIgnore] Method MappingConfiguration Atc.SourceGenerators.Annotations
[MapConfigOptions] Method MappingConfiguration Atc.SourceGenerators.Annotations
[MapTypes] Assembly, Class MappingConfiguration Atc.SourceGenerators.Annotations

Related Pages

🏠 Home

πŸ“– Getting Started

⚑ Generators

🎯 Examples

πŸ”— Integrations

πŸ” Reference

πŸ“‹ Feature Roadmaps


πŸ”— Resources

Clone this wiki locally