DependencyInjection.ReflectionExtensions
2025.10.10
.NET 8.0
This package targets .NET 8.0. The package is compatible with this framework or higher.
.NET Framework 4.8
This package targets .NET Framework 4.8. The package is compatible with this framework or higher.
dotnet add package DependencyInjection.ReflectionExtensions --version 2025.10.10
NuGet\Install-Package DependencyInjection.ReflectionExtensions -Version 2025.10.10
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="DependencyInjection.ReflectionExtensions" Version="2025.10.10" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DependencyInjection.ReflectionExtensions" Version="2025.10.10" />
<PackageReference Include="DependencyInjection.ReflectionExtensions" />
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 DependencyInjection.ReflectionExtensions --version 2025.10.10
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: DependencyInjection.ReflectionExtensions, 2025.10.10"
#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 DependencyInjection.ReflectionExtensions@2025.10.10
#: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=DependencyInjection.ReflectionExtensions&version=2025.10.10
#tool nuget:?package=DependencyInjection.ReflectionExtensions&version=2025.10.10
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
DevKit.Injection.Extensions
Biblioteca avanzada para la configuración automática de inyección de dependencias en aplicaciones .NET, con soporte para atributos declarativos, validaciones y patrones empresariales.
🚀 Características Principales
🎯 Registro Automático Avanzado
- Registro automático de servicios desde ensamblados
- Soporte para múltiples ciclos de vida (Scoped, Singleton, Transient)
- Filtros personalizados y configurables
- Logging detallado y configurable
📋 Sistema de Atributos Declarativo
- Atributos específicos por ciclo de vida (
[Singleton]
,[Scoped]
,[Transient]
) - Configuración declarativa con
[Service]
- Registro automático basado en atributos
- Soporte para reemplazo de servicios existentes
🛡️ Validaciones y Seguridad
- Detección automática de dependencias circulares
- Validación de tipos y configuraciones
- Manejo robusto de errores
- Logging de advertencias y problemas
⚙️ Funcionalidades Empresariales
- Patrón Decorator para servicios
- Factory methods personalizados
- Registro desde múltiples ensamblados
- Configuración fluida avanzada
📦 Instalación
dotnet add package DevKit.Injection.Extensions
🔧 Requisitos
- .NET Framework 4.8+ o .NET 8.0+
- Microsoft.Extensions.DependencyInjection.Abstractions
- Compatible con ASP.NET Core, Blazor, MAUI y aplicaciones de consola
🚀 Uso Rápido
📋 Registro con Atributos (Recomendado)
// 1. Marcar servicios con atributos
[Singleton]
public class CacheService : ICacheService
{
public void ClearCache() { }
}
[Scoped(typeof(IUserService))]
public class UserService : IUserService
{
public Task<User> GetUserAsync(int id) => Task.FromResult(new User());
}
[Transient]
public class EmailNotificationService
{
public void SendEmail(string to, string subject) { }
}
// 2. Registrar automáticamente
public void ConfigureServices(IServiceCollection services)
{
services.AddServicesWithAttributes(Assembly.GetExecutingAssembly());
}
⚡ Registro Automático Básico
public void ConfigureServices(IServiceCollection services)
{
// Registro simple desde ensamblado
services.AddFromAssembly(Assembly.GetExecutingAssembly());
// Con filtros personalizados
services.AddFromAssembly(
assembly: Assembly.GetExecutingAssembly(),
filter: type => type.Name.EndsWith("Service"),
LogTo: message => Console.WriteLine($"[DI] {message}"),
lifetime: ServiceLifetime.Scoped
);
}
🎯 Funcionalidades Avanzadas
🔧 Configuración Fluida
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureServices()
.RegisterFromAttributes(Assembly.GetExecutingAssembly())
.RegisterImplementationsOf<IRepository>(Assembly.GetExecutingAssembly())
.RegisterDecorator<IUserService, CachedUserService>()
.ValidateCircularDependencies();
}
🎨 Registro por Interfaz
// Registra todas las implementaciones de IRepository
services.AddImplementationsOf<IRepository>(
Assembly.GetExecutingAssembly(),
ServiceLifetime.Scoped
);
// Registra desde múltiples ensamblados
var assemblies = new[] {
Assembly.GetExecutingAssembly(),
typeof(ExternalService).Assembly
};
services.AddFromAssemblies(assemblies);
🏭 Factory Methods
services.ConfigureServices()
.RegisterFactory<IComplexService>(provider =>
{
var dependency = provider.GetRequiredService<IDependency>();
return new ComplexService(dependency, "custom-config");
}, ServiceLifetime.Singleton);
🎭 Patrón Decorator
// Servicio base
[Scoped]
public class UserService : IUserService
{
public Task<User> GetUserAsync(int id) => /* implementación */;
}
// Decorator con cache
public class CachedUserService : IUserService
{
private readonly IUserService _inner;
private readonly IMemoryCache _cache;
public CachedUserService(IUserService inner, IMemoryCache cache)
{
_inner = inner;
_cache = cache;
}
public Task<User> GetUserAsync(int id)
{
return _cache.GetOrCreateAsync($"user_{id}",
_ => _inner.GetUserAsync(id));
}
}
// Configuración
services.ConfigureServices()
.RegisterFromAttributes(Assembly.GetExecutingAssembly())
.RegisterDecorator<IUserService, CachedUserService>();
📋 Atributos Disponibles
Atributo | Descripción | Ejemplo |
---|---|---|
[Service] |
Configuración general | [Service(ServiceLifetime.Scoped)] |
[Singleton] |
Registro como Singleton | [Singleton(typeof(ICache))] |
[Scoped] |
Registro como Scoped | [Scoped] |
[Transient] |
Registro como Transient | [Transient(typeof(INotification))] |
🚀 Métodos de Extensión
Método | Descripción |
---|---|
AddFromAssembly |
Registro desde un ensamblado |
AddFromAssemblies |
Registro desde múltiples ensamblados |
AddServicesWithAttributes |
Registro basado en atributos |
AddImplementationsOf<T> |
Todas las implementaciones de una interfaz |
AddCurrentAssembly |
Registro automático del ensamblado actual |
ConfigureServices |
Configuración fluida avanzada |
🛡️ Validaciones y Debugging
Detección de Dependencias Circulares
services.ConfigureServices()
.RegisterFromAttributes(Assembly.GetExecutingAssembly())
.ValidateCircularDependencies(); // Lanza excepción si hay ciclos
Logging Detallado
services.AddFromAssembly(
Assembly.GetExecutingAssembly(),
LogTo: message => _LogTo.LogInformation("[DI] {Message}", message)
);
// Ver log de registros
var registrar = services.ConfigureServices();
registrar.RegisterFromAttributes(Assembly.GetExecutingAssembly());
var logs = registrar.GetRegistrationLog();
💡 Mejores Prácticas
🎯 Uso de Atributos
- Usar
[Singleton]
para servicios sin estado (caches, configuraciones) - Usar
[Scoped]
para servicios de negocio (repositories, services) - Usar
[Transient]
para servicios ligeros y sin estado compartido
🔍 Filtros Inteligentes
services.AddFromAssembly(
Assembly.GetExecutingAssembly(),
filter: type =>
type.Name.EndsWith("Service") ||
type.Name.EndsWith("Repository") ||
type.GetInterfaces().Any(i => i.Name.StartsWith("I"))
);
📊 Organización por Módulos
// Program.cs o Startup.cs
services.AddFromAssembly(typeof(BusinessLogic.IUserService).Assembly);
services.AddFromAssembly(typeof(DataAccess.IUserRepository).Assembly);
services.AddFromAssembly(typeof(Infrastructure.IEmailService).Assembly);
🔧 Casos de Uso Avanzados
Registro Condicional
services.AddFromAssembly(
Assembly.GetExecutingAssembly(),
filter: type =>
{
// Solo en desarrollo
if (Environment.IsDevelopment())
return !type.Name.Contains("Production");
// Solo servicios de producción
return !type.Name.Contains("Mock") && !type.Name.Contains("Test");
}
);
Múltiples Implementaciones
// Registrar todas las implementaciones de INotificationProvider
services.AddImplementationsOf<INotificationProvider>(Assembly.GetExecutingAssembly());
// Usar en runtime
public class NotificationService
{
public NotificationService(IEnumerable<INotificationProvider> providers)
{
// Usar todas las implementaciones
}
}
📚 Compatibilidad
- ✅ ASP.NET Core 3.1+
- ✅ Blazor Server/WASM
- ✅ MAUI
- ✅ Worker Services
- ✅ Console Applications
- ✅ .NET Framework 4.8+
🆚 Comparación con Otras Bibliotecas
Característica | DevKit.Injection | Scrutor | Autofac |
---|---|---|---|
Atributos Declarativos | ✅ | ❌ | ✅ |
Validación Circular | ✅ | ❌ | ✅ |
Patrón Decorator | ✅ | ✅ | ✅ |
Múltiples Ensamblados | ✅ | ✅ | ✅ |
.NET Framework | ✅ | ❌ | ✅ |
Configuración Fluida | ✅ | ✅ | ✅ |
📄 Licencia
Este proyecto está bajo licencia MIT. Consulta el archivo LICENSE para más detalles.
Product | Versions 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 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. |
.NET Framework | net48 is compatible. net481 was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
.NETFramework 4.8
-
net8.0
-
net9.0
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 |
---|---|---|
2025.10.10 | 80 | 10/10/2025 |
2025.8.19 | 178 | 8/19/2025 |
2025.8.13 | 162 | 8/13/2025 |
2025.7.13 | 208 | 7/14/2025 |
2025.6.12 | 323 | 6/11/2025 |
2025.6.11 | 319 | 6/11/2025 |
2025.5.24 | 119 | 5/24/2025 |
2025.5.23 | 100 | 5/23/2025 |
2025.5.16 | 270 | 5/15/2025 |
2025.5.15 | 244 | 5/15/2025 |
2025.5.14 | 250 | 5/14/2025 |
2025.5.13 | 259 | 5/13/2025 |