JZen.AutoInject 2.0.0

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

๐Ÿš€ AutoInject

.NET 8.0 License: MIT NuGet

๐ŸŽ‰ NEW v2.0: Smart Auto-Registration!
Stop writing constructor injection boilerplate AND manual DI registration! ๐Ÿ›‘
AutoInject now automatically discovers and registers your dependencies - zero configuration needed!

๐Ÿง  Smart Auto-Registration (NEW!)

The future of dependency injection is here! No more manual registration:

// Program.cs - Just this! ๐ŸŽฏ
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAutoInject();  // One line setup!

var app = builder.Build();
app.UseAutoInject();
app.Run();

// Your service - Zero configuration needed! โœจ
public class UserService : InjectBase
{
    [Injectable] private readonly IUserRepository? _repository;     // Auto-found!
    [Injectable] private readonly IEmailService? _emailService;     // Auto-registered!
    
    public async Task CreateUserAsync(string name)
    {
        var user = new User { Name = name };
        await _repository!.SaveAsync(user);           // Works automatically!
        _emailService!.SendWelcomeEmail(user);        // No setup required!
    }
}

๐ŸŽฏ How Smart Auto-Registration Works:

  1. ๐Ÿ” Discovers implementations automatically when needed
  2. ๐Ÿ“ Registers them as Scoped services on-the-fly
  3. ๐Ÿ’‰ Injects dependencies instantly
  4. ๐Ÿš€ Caches mappings for blazing-fast performance
  5. ๐Ÿงน Manages scoping and disposal automatically

๐Ÿ†š Before vs After:

Before (Manual Hell) After (Smart Auto-Registration)
50+ lines of registration 2 lines total
Manual interface mapping Automatic discovery
Assembly scanning setup Zero configuration
Startup performance hit Lazy, on-demand loading
Maintenance nightmare Self-maintaining

๐Ÿ“– Complete Smart Auto-Registration Guide

AutoInject now automatically discovers and registers your dependencies - zero configuration needed!

๐Ÿง  Smart Auto-Registration (NEW!)

The old way: Constructor injection hell + Manual registration nightmare ๐Ÿ˜ค The future of dependency injection is here! No more manual registration: // Program.cs - Manual registration hell services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IEmailService, EmailService>(); services.AddScoped<IPaymentService, PaymentService>(); services.AddScoped<INotificationService, NotificationService>(); services.AddScoped<ICacheService, CacheService>(); // ... 50+ more lines

// Your service - Constructor injection hell```csharp // Program.cs - Just this! ๐ŸŽฏ var builder = WebApplication.CreateBuilder(args); builder.Services.AddAutoInject(); // One line setup!

var app = builder.Build(); app.UseAutoInject(); app.Run();

// Your service - Zero configuration needed! โœจ public class UserService : InjectBase { [Injectable] private readonly IUserRepository? _repository; // Auto-found! [Injectable] private readonly IEmailService? _emailService; // Auto-registered!

public async Task CreateUserAsync(string name)
{
    var user = new User { Name = name };
    await _repository!.SaveAsync(user);           // Works automatically!
    _emailService!.SendWelcomeEmail(user);        // No setup required!
}

}


**The AutoInject way:** Zero configuration + Clean code โœจ
1. ๐Ÿ” **Discovers** implementations automatically when needed
2. ๐Ÿ“ **R// Program.cs - Just this!
builder.Services.AddAutoInject();
app.UseAutoInject();

// Your service - Clean and simple3. ๐Ÿ’‰ **Injects** dependencies instantly
4. ๐Ÿš€ **Caches** mappings for blazing-fast performance
5. ๐Ÿงน **Manages** scoping and disposal automatically

**๐Ÿ†š Before vs After:**

| Before (Manual Hell) | After (Smart Auto-Registration) |
|----------------------|----------------------------------|
| 50+ lines of registration | 2 lines total |
| Manual interface mapping | Automatic discovery |
| Assembly scanning setup | Zero configuration |
| Startup performance hit | Lazy, on-demand loading |
| Maintenance nightmare | Self-maintaining |

[๐Ÿ“– Complete Smart Auto-Registration Guide](SMART_AUTO_REGISTRATION.md)



**The AutoInject way:** Zero configuration + Clean code โœจ

```csharp
// Program.cs - Just this!
builder.Services.AddAutoInject();
app.UseAutoInject();

// Your service - Clean and simple
public class OrderService : InjectBase
{
    [Injectable] private readonly IRepository? _repository;
    [Injectable] private readonly IEmailService? _emailService;
    [Injectable] private readonly IPaymentService? _paymentService;
    [Injectable] private readonly INotificationService? _notificationService;

    public async Task ProcessOrderAsync(int orderId)
    {
        _logger.LogInformation("Processing order {OrderId}", orderId);
        await _repository!.SaveAsync(order);
        _emailService!.SendConfirmation(order);
    }
}

๐Ÿš€ Quick Start

๐Ÿš€ Quick Start

1. Install the Package

dotnet add package JZen.AutoInject
### 2. Configure (Two Lines!)

### 2. Configure (Two Lines!)
```csharp
builder.Services.AddAutoInject();  // ๐ŸŽฏ Smart Auto-Registration enabled!
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAutoInject();  // ๐ŸŽฏ Smart Auto-Registration enabled!
app.UseAutoInject();               // ๐Ÿš€ Factory configured!
var app = builder.Build();
app.UseAutoInject();               // ๐Ÿš€ Factory configured!
app.Run();

3. Use in Your Classes

    [Injectable] private readonly IProductRepository? _repository;  // Auto-found!
    [Injectable] private readonly ICacheService? _cache;            // Auto-registered!
    [Injectable] private readonly IProductRepository? _repository;  // Auto-found!
    [Injectable] private readonly ICacheService? _cache;            // Auto-registered!
    
    public async Task<Product> GetProductAsync(int id)
    {
        _logger.LogInformation("Getting product {Id}", id);
        
        var cached = _cache!.Get<Product>($"product_{id}");
        if (cached != null) return cached;
        
        var product = await _repository!.GetByIdAsync(id);
        _cache.Set($"product_{id}", product);
        
        return product;
   
**That's it! No manual registration needed!** ๐ŸŽ‰}

That's it! No manual registration needed! ๐ŸŽ‰

๐ŸŽ›๏ธ Features

๐Ÿง  Smart Auto-Registration (NEW!)

  • Zero configuration - Automatically finds implementations
  • On-demand discovery - Only registers what you actually use
  • Performance optimized - Caches mappings for speed
  • Cross-assembly support - Works with any loaded assembly

๐Ÿง  Smart Auto-Registration (NEW!)

  • Zero configuration - Automatically finds implementations
  • On-demand discovery - Only registers what you actually use
  • Performance optimized - Caches mappings for speed

l

  • Clean, readable code

  • InjectBase: Automatic injection on construction (recommended)

  • InjectBase: Automatic injection on construction (recommended)

  • [AutoInject]: Factory-based injection

  • Manual: Call Factory.InjectDependencies(this)

  • Automatic ILogger injection via InjectBase

  • Automatic ILogger injection via InjectBase

  • Type-safe logger instances

  • Zero configuration

โœ… Scoped Management

  • HTTP request scoping
  • Automatic disposal
  • Thread-safe operations

โœ… ASP.NET Core Integration

  • Works with existing DI container
  • Middleware support

โœ… Backward Compatibility

  • Mix with manual registrations
  • Existing code keeps working
  • Gradual migration support- Controller injection

โœ… Backward Compatibility

  • Mix with manual registrations
  • Existing code keeps working
  • Gradual migration support

๐Ÿ“‹ Usage Examples

Basic Service

public class EmailService : InjectBase
{
    [Injectable] private readonly IEmailProvider? _provider;
    [Injectable] private readonly ITemplateEngine? _templates;
    
    public async Task SendAsync(string to, string subject, string body)
    {
        _logger.LogInformation("Sending email to {To}", to);
        
        var template = _templates!.Render(body);
        await _provider!.SendAsync(to, subject, template);
    }
}

Controller Integration

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly UserService _userService = new();
    
    [HttpPost]
    public async Task<IActionResult> CreateUser(CreateUserRequest request)
    {
        var user = await _userService.CreateUserAsync(request.Name);
        return Ok(user);
    }
}

Background Service

public class OrderProcessingService : BackgroundService, InjectBase
{
    [Injectable] private readonly IOrderRepository? _orders;
    [Injectable] private readonly IPaymentService? _payments;
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var pendingOrders = await _orders!.GetPendingAsync();
            
            foreach (var order in pendingOrders)
            {
                await _payments!.ProcessAsync(order);
                _logger.LogInformation("Processed order {OrderId}", order.Id);
            }
            
            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
        }
    }
}

๐Ÿ”ง Advanced Configuration

Mixed Registration

// Program.cs - Mix manual and auto registration
builder.Services.AddAutoInject();
builder.Services.AddScoped<ISpecialService, CustomImplementation>(); // Manual
// Other services will be auto-registered

public class MyService : InjectBase
{
    [Injectable] private readonly ISpecialService? _special;      // Uses manual registration
    [Injectable] private readonly IRegularService? _regular;     // Auto-registered
}

Custom Factory Configuration

// For non-web applications
var services = new ServiceCollection();
services.AddLogging();
services.AddAutoInject();

var serviceProvider = services.ConfigureAutoInject();

// Now you can use InjectBase classes
var myService = new MyService();

Manual Injection

public class LegacyClass
{
    [Injectable] private readonly IRepository? _repository;
    
    public LegacyClass()
    {
        Factory.InjectDependencies(this); // Manual injection
    }
}

๐ŸŽฏ When to Use AutoInject

โœ… Perfect For:

  • Rapid prototyping - Get up and running fast
  • Clean architecture - Focus on business logic
  • Large applications - Reduce boilerplate significantly
  • Convention over configuration - Sensible defaults

โš ๏ธ Consider Alternatives When:

  • You need multiple implementations of the same interface
  • Complex lifetime management requirements
  • Performance-critical applications with strict DI requirements
  • You prefer explicit registration for all services

๐Ÿ”„ Migration Guide

๐ŸŽ‰ Upgrading to v2.0 (Smart Auto-Registration)

Old way (v1.x) - Manual registration:

// Program.cs - v1.x
builder.Services.AddInjectBaseClasses(Assembly.GetExecutingAssembly()); // โŒ Obsolete

New way (v2.0) - Smart Auto-Registration:

// Program.cs - v2.0
builder.Services.AddAutoInject(); // โœ… Recommended
app.UseAutoInject();

Benefits of upgrading:

  • ๐Ÿš€ 80% less configuration code
  • โšก Better performance (lazy loading)
  • ๐Ÿงน Self-maintaining (no manual updates needed)
  • ๐Ÿ” Cross-assembly discovery
  • ๐ŸŽฏ Zero breaking changes (your existing code works as-is)

โš ๏ธ Obsolete Methods

The following methods are now obsolete and will be removed in v3.0:

// โŒ Obsolete - Don't use these anymore
services.AddInjectBaseClasses(assembly);
services.AddInjectBaseClasses(assemblies);
services.AddInjectBaseClasses();

Migration is simple:

// Before
services.AddInjectBaseClasses(Assembly.GetExecutingAssembly());

// After
services.AddAutoInject(); // That's it!

๐ŸŽ‰ Upgrading to v2.0 (Smart Auto-Registration)

Old way (v1.x) - Manual registration:

// Program.cs - v1.x
builder.Services.AddInjectBaseClasses(Assembly.GetExecutingAssembly()); // โŒ Obsolete

New way (v2.0) - Smart Auto-Registration:

// Program.cs - v2.0
builder.Services.AddAutoInject(); // โœ… Recommended
app.UseAutoInject();

Benefits of upgrading:

  • ๐Ÿš€ 80% less configuration code
  • โšก Better performance (lazy loading)
  • ๐Ÿงน Self-maintaining (no manual updates needed)
  • ๐Ÿ” Cross-assembly discovery
  • ๐ŸŽฏ Zero breaking changes (your existing code works as-is)

โš ๏ธ Obsolete Methods

The following methods are now obsolete and will be removed in v3.0: // Before - Program.cs (50+ lines)

// โŒ Obsolete - Don't use these anymore
services.AddInjectBaseClasses(assembly);
// ... dozens more registrationsassemblies);
services.AddInjectBaseClasses();
// After - Program.cs (2 lines)
services.AddAutoInject(); // Replaces all manual registrations!
app.UseAutoInject();
**Migration is simple:**
```csharp
// Before
services.AddInjectBaseClasses(Assembly.GetExecutingAssembly());

// After
services.AddAutoInject(); // That's it!

From Constructor Injection

// Before
public class OrderService
{
    private readonly IRepository _repo;
    private readonly IEmailService _email;
    
    public OrderService(IRepository repo, IEmailService email)
    {
        _repo = repo;
        _email = email;
    }
}

// After
public class OrderService : InjectBase
{
    [Injectable] private readonly IRepository? _repo;
    [Injectable] private readonly IEmailService? _email;
}

From Manual DI Registration

// Before - Program.cs (50+ lines)
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<INotificationService, NotificationService>();
// ... dozens more registrations

// After - Program.cs (2 lines)
services.AddAutoInject(); // Replaces all manual registrations!
app.UseAutoInject();

๐Ÿ“Š Performance

  • Startup: Minimal overhead, lazy discovery
  • Runtime: Cached type mappings for fast resolution
  • Memory: Efficient scoping and disposal
  • Throughput: Comparable to native DI container

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Inspired by the need for cleaner dependency injection in .NET
  • Built on top of Microsoft.Extensions.DependencyInjection
  • Community feedback and contributions

Made with โค๏ธ for the .NET community

โญ Star this repo if you find it useful!

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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
2.0.1 151 6/3/2025
2.0.0 143 6/3/2025
1.1.0 144 6/3/2025
1.0.0 150 5/29/2025

🎉 v2.0.0 - SMART AUTO-REGISTRATION: Revolutionary zero-configuration dependency injection! โœจ Automatically discovers and registers dependencies on-demand โœจ Cross-assembly implementation discovery โœจ Performance-optimized with intelligent caching โœจ 80% less configuration code โœจ Backward compatible - existing code works unchanged โš ๏ธ AddInjectBaseClasses() methods marked obsolete (use AddAutoInject() instead)