Aoxe.DependencyInjection.Extensions provides extension methods for Microsoft's Dependency Injection container to simplify service registration with Lazy<T> support. These extensions allow for deferred instantiation of services, improving performance by delaying object creation until it's actually needed.
- Extension methods to register services with Lazy<T>
- AddSingletonWithLazy
- AddScopedWithLazy
- AddTransientWithLazy
- Support for both type and factory-based registrations
- Simplifies the use of Lazy<T> in dependency injection scenarios
To install the package, add the following to your project file:
<PackageReference Include="Aoxe.DependencyInjection.Extensions" Version="2024.1.0" />
Or use the .NET CLI:
dotnet add package Aoxe.DependencyInjection.Extensions
First, include the namespace:
using Aoxe.DependencyInjection.Extensions;
Use the 'AddSingletonWithLazy' method to register singleton services with Lazy<T> support:
services.AddSingletonWithLazy<IMyService, MyServiceImplementation>();
For scoped services, use the 'AddScopedWithLazy' method:
services.AddScopedWithLazy<IMyService, MyServiceImplementation>();
For transient services, use the 'AddTransientWithLazy' method:
services.AddTransientWithLazy<IMyService, MyServiceImplementation>();
Inject Lazy<T> into your classes to defer service instantiation:
public class MyController
{
private readonly Lazy<IMyService> _myService;
public MyController(Lazy<IMyService> myService)
{
_myService = myService;
}
public void DoWork()
{
// The IMyService instance is created only when accessed
_myService.Value.PerformOperation();
}
}
Refer to the unit tests for more examples:
- AddSingletonUnitTest.cs
- AddScopedUnitTest.cs
- AddTransientUnitTest.cs
This project is licensed under the MIT License.
Contributions are welcome! Please submit issues or pull requests to the GitHub repository.
Thank`s for JetBrains for the great support in providing assistance and user-friendly environment for my open source projects.