ProviderAttribute
NexusLabs.Needlr.Generators¶
ProviderAttribute Class¶
Marks an interface or partial class as a Provider - a strongly-typed service locator.
Inheritance System.Object 🡒 System.Attribute 🡒 ProviderAttribute
Remarks¶
A Provider is a compile-time generated class that provides strongly-typed access to
services registered in the dependency injection container. Unlike using
IServiceProvider.GetService<T>() directly, Providers offer:
- Compile-time verification that required services are registered
- IntelliSense and IDE support for available services
- Easy mocking in unit tests
Providers are always registered as Singletons. All service properties are resolved via constructor injection at Provider construction time (fail-fast). For creating new instances on demand, use the Factories parameter to generate factory properties.
Usage modes: 1. Interface definition: Apply to an interface with get-only properties. The generator creates an implementing class.
[Provider]
public interface IOrderServicesProvider
{
IOrderRepository Repository { get; }
IOrderValidator Validator { get; }
}
// Generates: OrderServicesProvider class
[Provider(typeof(IOrderRepository), typeof(IOrderValidator))]
public partial class OrderDependenciesProvider { }
// Generates: IOrderDependenciesProvider interface + implementation
Constructors¶
ProviderAttribute() Constructor¶
Creates a Provider attribute for an interface definition. Define service properties directly on the interface.
ProviderAttribute(Type[]) Constructor¶
Creates a Provider with the specified required service types. Use on a partial class to auto-generate interface and implementation.
Parameters¶
requiredServices System.Type[]
Service types that must be registered in the container. Property names are derived from type names (e.g., IOrderRepository → OrderRepository).
Properties¶
ProviderAttribute.Collections Property¶
Service types to resolve as IEnumerable<T>.
Property Value¶
Remarks¶
Properties for these services use GetServices<T>() and return
all registered implementations.
ProviderAttribute.Factories Property¶
Types to generate factories for, enabling creation of new instances.
Property Value¶
Remarks¶
For each type specified:
- If the type has [GenerateFactory], the existing factory is used.
- Otherwise, a factory (IXxxFactory) is generated automatically.
This allows the Provider to create new instances while remaining a Singleton.
ProviderAttribute.Optional Property¶
Service types that may not be registered. Properties are nullable.
Property Value¶
Remarks¶
Properties for these services use GetService<T>() and return null
if the service is not registered.
ProviderAttribute.Required Property¶
Service types that must be registered. Resolution failure throws at startup.
Property Value¶
Remarks¶
Properties for these services use GetRequiredService<T>().
If any service is not registered, the application fails to start.