NexusLabs.Needlr.Extensions.Logging 0.0.2-alpha-0011

This is a prerelease version of NexusLabs.Needlr.Extensions.Logging.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package NexusLabs.Needlr.Extensions.Logging --version 0.0.2-alpha-0011
                    
NuGet\Install-Package NexusLabs.Needlr.Extensions.Logging -Version 0.0.2-alpha-0011
                    
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="NexusLabs.Needlr.Extensions.Logging" Version="0.0.2-alpha-0011" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NexusLabs.Needlr.Extensions.Logging" Version="0.0.2-alpha-0011" />
                    
Directory.Packages.props
<PackageReference Include="NexusLabs.Needlr.Extensions.Logging" />
                    
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 NexusLabs.Needlr.Extensions.Logging --version 0.0.2-alpha-0011
                    
#r "nuget: NexusLabs.Needlr.Extensions.Logging, 0.0.2-alpha-0011"
                    
#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 NexusLabs.Needlr.Extensions.Logging@0.0.2-alpha-0011
                    
#: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=NexusLabs.Needlr.Extensions.Logging&version=0.0.2-alpha-0011&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=NexusLabs.Needlr.Extensions.Logging&version=0.0.2-alpha-0011&prerelease
                    
Install as a Cake Tool

Needlr

Needlr

Needlr is an opinionated fluent dependency injection library for .NET that provides automatic service registration and web application setup through a simple, discoverable API. It's designed to minimize boilerplate code by defaulting to registering types from scanned assemblies automatically.

Needlr is source-generation-first: The default approach uses compile-time source generation for AOT compatibility and optimal performance. Reflection-based discovery is available as an explicit opt-in for dynamic scenarios.

Features

  • Source Generation First: Compile-time type discovery for AOT/trimming compatibility
  • Reflection as Opt-In: Dynamic type discovery available when needed
  • Automatic Service Discovery: Automatically registers services from assemblies using conventions
  • Fluent API: Chain-able configuration methods for clean, readable setup
  • ASP.NET Core Integration: Seamless web application creation and configuration
  • Plugin System: Extensible architecture for modular applications
  • Multiple Type Registrars: Built-in support for default registration and Scrutor-based scanning
  • Flexible Filtering: Control which types get registered automatically
  • Decorator Pattern Support: Built-in support for service decoration with AddDecorator extension
  • Post-Build Plugins: Execute configuration after the main service collection has been built
  • Configuration Integration: Automatic IConfiguration registration and support
  • Assembly Provider: Flexible assembly scanning with filtering and sorting options

📚 Documentation

Getting Started Guide → - New to Needlr? Start here for a step-by-step introduction.

Additional documentation:

Quick Start

For AOT-compatible applications with compile-time type discovery:

using NexusLabs.Needlr.AspNet;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.SourceGen;

var webApplication = new Syringe()
    .UsingSourceGen()
    .ForWebApplication()
    .BuildWebApplication();

await webApplication.RunAsync();

Reflection-Based (Dynamic Scenarios)

For applications that need runtime type discovery:

using NexusLabs.Needlr.AspNet;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.Reflection;

var webApplication = new Syringe()
    .UsingReflection()
    .ForWebApplication()
    .BuildWebApplication();

await webApplication.RunAsync();

Auto-Configuration (Bundle)

For convenience with automatic fallback from source-gen to reflection:

using NexusLabs.Needlr.AspNet;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.Bundle;

var webApplication = new Syringe()
    .UsingAutoConfiguration()
    .ForWebApplication()
    .BuildWebApplication();

await webApplication.RunAsync();

Installation

Add the core package and choose your discovery strategy:


<PackageReference Include="NexusLabs.Needlr.Injection" />


<PackageReference Include="NexusLabs.Needlr.Injection.SourceGen" />
<PackageReference Include="NexusLabs.Needlr.Generators" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<PackageReference Include="NexusLabs.Needlr.Generators.Attributes" />


<PackageReference Include="NexusLabs.Needlr.Injection.Reflection" />


<PackageReference Include="NexusLabs.Needlr.Injection.Bundle" />


<PackageReference Include="NexusLabs.Needlr.AspNet" />


<PackageReference Include="NexusLabs.Needlr.Injection.Scrutor" />


<PackageReference Include="NexusLabs.Needlr.Carter" />


<PackageReference Include="NexusLabs.Needlr.SignalR" />


<PackageReference Include="NexusLabs.Needlr.SemanticKernel" />

Core Concepts

Syringe

The Syringe class is the main entry point for configuring dependency injection in Needlr. It provides a fluent API for setting up:

  • Discovery Strategy: Source generation (.UsingSourceGen()) or reflection (.UsingReflection())
  • Type Registrars: How services are registered (default or Scrutor-based)
  • Type Filterers: Which types should be registered automatically
  • Assembly Providers: Which assemblies to scan for services
// Source generation approach (recommended)
var syringe = new Syringe()
    .UsingSourceGen()
    .UsingAssemblyProvider(builder => builder
        .MatchingAssemblies(x => x.Contains("MyApp"))
        .Build());

// Reflection approach (dynamic scenarios)
var syringe = new Syringe()
    .UsingReflection()
    .UsingScrutorTypeRegistrar()
    .UsingAssemblyProvider(builder => builder
        .MatchingAssemblies(x => x.Contains("MyApp"))
        .Build());

WebApplicationSyringe

For web applications, use ForWebApplication() to transition to web-specific configuration:

var webApp = new Syringe()
    .UsingSourceGen()
    .ForWebApplication()
    .UsingOptions(() => CreateWebApplicationOptions.Default)
    .BuildWebApplication();

Service Registration

Automatic Registration

Services are automatically registered based on conventions. By default, Needlr will:

  • Register classes as both themselves and their interfaces
  • Use appropriate lifetimes (Transient/Singleton based on type filtering)
  • Skip types marked with [DoNotAutoRegister]

Preventing Auto-Registration

Use the [DoNotAutoRegister] attribute to exclude types from automatic registration. This is typically done when you need manual control over service registration:

[DoNotAutoRegister]
public class ManuallyRegisteredService
{
    // This won't be automatically registered
}

Custom Services

By default, a custom class you create (public or internal) will get picked up automatically and be available on the dependency container:

internal class WeatherProvider
{
    private readonly IConfiguration _config;
    
    public WeatherProvider(IConfiguration config)
    {
        _config = config;
    }
    
    public WeatherData GetWeather()
    {
        // Implementation
    }
}

The above class would be available for use in minimal APIs and can be injected into other types resolved from the dependency container.

Manual Service Registration

While Needlr automatically registers services by convention, you may need to manually register services for more complex scenarios like decorator patterns, conditional registration, or when you need precise control over service lifetimes and configurations.

Preventing Auto-Registration

Use the [DoNotAutoRegister] attribute to exclude types from automatic registration:

using NexusLabs.Needlr;

[DoNotAutoRegister]
public sealed class MyService : IMyService
{
    public void DoSomething()
    {
        Console.WriteLine("Hello, from Dev Leader!");
    }
}

Manual Registration with IServiceCollectionPlugin

Create a plugin that implements IServiceCollectionPlugin to manually configure services:

using Microsoft.Extensions.DependencyInjection;
using NexusLabs.Needlr;

internal sealed class MyPlugin : IServiceCollectionPlugin
{
    public void Configure(ServiceCollectionPluginOptions options)
    {
        // Register service manually as singleton
        options.Services.AddSingleton<IMyService, MyService>();
    }
}

Decorator Pattern Example

Here's a complete example showing manual registration with a decorator pattern:

using Microsoft.Extensions.DependencyInjection;
using NexusLabs.Needlr;
using NexusLabs.Needlr.Injection;

// Interface
public interface IMyService
{
    void DoSomething();
}

// Base service implementation
[DoNotAutoRegister]
public sealed class MyService : IMyService
{
    public void DoSomething()
    {
        Console.WriteLine("Hello, from Dev Leader!");
    }
}

// Decorator that adds additional behavior
[DoNotAutoRegister]
public sealed class MyDecorator(IMyService wrapped) : IMyService
{
    public void DoSomething()
    {
        Console.WriteLine("---BEFORE---");
        wrapped.DoSomething();
        Console.WriteLine("---AFTER---");
    }
}

// Plugin for manual registration
internal sealed class MyPlugin : IServiceCollectionPlugin
{
    public void Configure(ServiceCollectionPluginOptions options)
    {
        options.Services.AddSingleton<MyService>();
        options.Services.AddSingleton<IMyService, MyDecorator>(s => 
            new MyDecorator(s.GetRequiredService<MyService>()));
    }
}

// Usage (with source generation)
var serviceProvider = new Syringe()
    .UsingSourceGen()
    .BuildServiceProvider();
serviceProvider.GetRequiredService<IMyService>().DoSomething();
// Output:
// ---BEFORE---
// Hello, from Dev Leader!
// ---AFTER---

The IServiceCollectionPlugin is automatically discovered and registered by Needlr, so you don't need to manually register the plugin itself.

Manual Registration with Scrutor Decoration

When using Scrutor type registrar, you can leverage Scrutor's decoration extensions for cleaner decorator pattern implementation:

using Microsoft.Extensions.DependencyInjection;
using NexusLabs.Needlr;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.Scrutor;

// Interface and service implementations (same as above example)
// ...

// Plugin using Scrutor decoration extensions
internal sealed class MyScrutorPlugin : IServiceCollectionPlugin
{
    public void Configure(ServiceCollectionPluginOptions options)
    {
        // Register the base service first
        options.Services.AddSingleton<IMyService, MyService>();
        
        // Use Scrutor to decorate the service
        options.Services.Decorate<IMyService, MyDecorator>();
    }
}

// Usage with Scrutor type registrar (requires reflection)
var serviceProvider = new Syringe()
    .UsingReflection()
    .UsingScrutorTypeRegistrar()
    .BuildServiceProvider();

serviceProvider.GetRequiredService<IMyService>().DoSomething();
// Output:
// ---BEFORE---
// Hello, from Dev Leader!
// ---AFTER---

This approach is cleaner than manual decorator registration as Scrutor handles the complex dependency injection logic internally.

Using AddDecorator Extension

Needlr provides a convenient AddDecorator extension method that simplifies decorator registration:

using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.SourceGen;

var serviceProvider = new Syringe()
    .UsingSourceGen()
    .UsingPostPluginRegistrationCallback(services =>
    {
        // Register the base service
        services.AddSingleton<IMyService, MyService>();
    })
    .AddDecorator<IMyService, MyDecorator>()
    .BuildServiceProvider();

serviceProvider.GetRequiredService<IMyService>().DoSomething();
// Output:
// ---BEFORE---
// Hello, from Dev Leader!
// ---AFTER---

The AddDecorator extension automatically wraps the existing service registration with the decorator, preserving the original service's lifetime.

Plugin System

Needlr supports a plugin architecture for modular applications:

Web Application Plugins

internal sealed class WeatherPlugin : IWebApplicationPlugin
{
    public void Configure(WebApplicationPluginOptions options)
    {
        options.WebApplication.MapGet("/weather", (WeatherProvider weatherProvider) =>
        {
            return Results.Ok(weatherProvider.GetWeather());
        });
    }
}

Web Application Builder Plugins

public sealed class CarterWebApplicationBuilderPlugin : IWebApplicationBuilderPlugin
{
    public void Configure(WebApplicationBuilderPluginOptions options)
    {
        options.Logger.LogInformation("Configuring Carter services...");
        options.Builder.Services.AddCarter();
    }
}

Examples

Minimal Web API (Source Generation)

The following example has a custom type automatically registered and a minimal API that will consume it:

using NexusLabs.Needlr.AspNet;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.SourceGen;

var webApplication = new Syringe()
    .UsingSourceGen()
    .ForWebApplication()
    .BuildWebApplication();
await webApplication.RunAsync();

internal sealed class WeatherPlugin : IWebApplicationPlugin
{
    public void Configure(WebApplicationPluginOptions options)
    {
        options.WebApplication.MapGet("/weather", (WeatherProvider weatherProvider) =>
        {
            return Results.Ok(weatherProvider.GetWeather());
        });
    }
}

internal sealed class WeatherProvider(IConfiguration config)
{
    public object GetWeather()
    {
        var weatherConfig = config.GetSection("Weather");
        return new
        {
            TemperatureC = weatherConfig.GetValue<double>("TemperatureCelsius"),
            Summary = weatherConfig.GetValue<string>("Summary"),
        };
    }
}

Fluent Configuration (Reflection with Scrutor)

using NexusLabs.Needlr.AspNet;
using NexusLabs.Needlr.Injection;
using NexusLabs.Needlr.Injection.Reflection;
using NexusLabs.Needlr.Injection.Scrutor;

var webApplication = new Syringe()
    .UsingReflection()
    .UsingScrutorTypeRegistrar()
    .UsingAssemblyProvider(builder => builder
        .MatchingAssemblies(x =>
            x.Contains("NexusLabs", StringComparison.OrdinalIgnoreCase) ||
            x.Contains("MyApp", StringComparison.OrdinalIgnoreCase))
        .UseLibTestEntrySorting()
        .Build())
    .UsingAdditionalAssemblies(additionalAssemblies: [])
    .ForWebApplication()
    .UsingOptions(() => CreateWebApplicationOptions
        .Default
        .UsingStartupConsoleLogger())
    .BuildWebApplication();

await webApplication.RunAsync();

Source Generation vs Reflection

Feature Source Generation Reflection
AOT Compatible ✅ Yes ❌ No
Trimming Safe ✅ Yes ❌ No
Startup Performance ✅ Faster ⚠️ Slower
Dynamic Plugin Loading ❌ No ✅ Yes
Runtime Assembly Scanning ❌ No ✅ Yes

Use Source Generation when:

  • Building AOT-compiled applications
  • Targeting trimmed/self-contained deployments
  • You want faster startup times
  • All plugins are known at compile time

Use Reflection when:

  • Loading plugins dynamically at runtime
  • Scanning assemblies not known at compile time
  • Using Scrutor for advanced registration patterns

Requirements

  • .NET 9 or later
  • C# 13.0 or later
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in 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
0.0.2-alpha-0032 0 4/13/2026
0.0.2-alpha-0031 0 4/13/2026
0.0.2-alpha-0030 0 4/13/2026
0.0.2-alpha-0029 25 4/12/2026
0.0.2-alpha-0028 26 4/12/2026
0.0.2-alpha-0027 47 4/11/2026
0.0.2-alpha-0026 31 4/11/2026
0.0.2-alpha-0025 177 3/4/2026
0.0.2-alpha-0024 51 3/3/2026
0.0.2-alpha-0023 55 3/2/2026
0.0.2-alpha-0022 47 3/2/2026
0.0.2-alpha-0021 49 3/2/2026
0.0.2-alpha-0020 44 3/1/2026
0.0.2-alpha-0019 49 3/1/2026
0.0.2-alpha-0018 54 1/30/2026
0.0.2-alpha-0017 57 1/27/2026
0.0.2-alpha-0016 59 1/24/2026
0.0.2-alpha-0015 63 1/23/2026
0.0.2-alpha-0014 58 1/23/2026
0.0.2-alpha-0011 61 1/23/2026
Loading failed