AutoInject simplifies .NET dependency injection by automating service resolution, reducing boilerplate, and supporting attribute-based injection.
$ dotnet add package Campsis.AutoInjectAutoInject is a lightweight and efficient dependency injection automation library for .NET. It eliminates the need for manual service registration by automatically discovering and injecting services using custom attributes.
[Singleton], [Scoped], or [Transient] attributes.IServiceCollection..NET CLI
dotnet add package Campsis.AutoInject
Or Package Manager Console:
Install-Package Campsis.AutoInject
Call UseAutoInjection() in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.UseAutoInjection();
var app = builder.Build();
app.Run();
Or specify a target assembly:
builder.Services.UseAutoInjection(typeof(MyService).Assembly);
Define your services with [Singleton], [Scoped], or [Transient] attributes:
[Singleton(typeof(IMyService))]
public class MyService : IMyService { }
[Scoped(typeof(IRepository))]
public class Repository : IRepository { }
[Transient(typeof(ILogger))]
public class Logger : ILogger { }
If no ServiceType is provided, AutoInject will register an instance.
[Singleton]
public class Configs { }
This registers Configs as a singleton instance, allowing it to be injected without an interface:
var configs = serviceProvider.GetService<Configs>();
AutoInject supports keyed dependency injection:
[Singleton(typeof(IStorageBroker), "SQL")]
public class SqlStorageBroker : IStorageBroker
{
public async ValueTask<string> InsertStudentAsync(string student)
{
await Task.Delay(10); // Simulate async operation
return $"Student {student} inserted sql.";
}
}
[Singleton(typeof(IStorageBroker), "MONGO")]
public class MongoStorageBroker : IStorageBroker
{
public async ValueTask<string> InsertStudentAsync(string student)
{
await Task.Delay(10); // Simulate async operation
return $"Student {student} inserted to mongo.";
}
}
Then resolve the service by key:
var cache = serviceProvider.GetRequiredKeyedService<ICacheService>("Redis");
Or consume the services in other classes:
[Singleton(typeof(IStudentService))]
public class StudentService(
[FromKeyedServices("SQL")] IStorageBroker sqlStorageBroker,
[FromKeyedServices("MONGO")] IStorageBroker mongoStorageBroker) : IStudentService
{
public ValueTask<string> InsertStudentIntoMongoAsync(string student) =>
mongoStorageBroker.InsertStudentAsync(student);
public ValueTask<string> InsertStudentIntoSQLAsync(string student) =>
sqlStorageBroker.InsertStudentAsync(student);
}
[Singleton], [Scoped], or [Transient] attributes.WithKey parameter is provided.UseAutoInjection() scans the calling assembly.UseAutoInjection(Assembly assembly) to target a specific assembly.AutoInject is licensed under the MIT License.
We welcome contributions! Feel free to submit issues or pull requests.
Happy coding! 🚀