Skip to content

DeferToContainerAttribute

NexusLabs.Needlr

NexusLabs.Needlr

DeferToContainerAttribute Class

Specifies constructor parameter types for a partial class whose constructor will be generated by another source generator.

public sealed class DeferToContainerAttribute : System.Attribute

Inheritance System.Object 🡒 System.Attribute 🡒 DeferToContainerAttribute

Example

// Your partial class - another generator will add a primary constructor
[DeferToContainer(typeof(IRepository), typeof(ILogger<MyService>))]
[GeneratedService]  // This triggers another source generator
public partial class MyService { }

// The other generator produces:
// public partial class MyService(IRepository repository, ILogger<MyService> logger) { }

// Needlr generates factory based on your [DeferToContainer] declaration:
// sp => new MyService(
//     sp.GetRequiredService<IRepository>(),
//     sp.GetRequiredService<ILogger<MyService>>())

Remarks

Use this attribute when your partial class receives a constructor from another source generator (e.g., a code generator that adds a primary constructor based on an attribute). Since Needlr's source generator cannot see constructors added by other generators, you must explicitly declare the expected constructor parameter types.

Needlr will generate a factory that calls the constructor with the specified parameter types, resolving each dependency from the service provider.

If the declared parameter types don't match the actual generated constructor, the build will fail with a compile error.

Constructors

DeferToContainerAttribute(Type[]) Constructor

Initializes a new instance of DeferToContainerAttribute with the specified constructor parameter types.

public DeferToContainerAttribute(params System.Type[] constructorParameterTypes);

Parameters

constructorParameterTypes System.Type[]

The types of the constructor parameters in order. Each type will be resolved from the service provider when creating an instance.

Properties

DeferToContainerAttribute.ConstructorParameterTypes Property

Gets the constructor parameter types in order.

public System.Type[] ConstructorParameterTypes { get; }

Property Value

System.Type[]

Remarks

These types are used by the source generator to create a factory delegate that resolves each parameter from the service provider and passes them to the constructor.