Annotation Service Builder is an ASP.NET library that simplifies dependency injection by using custom annotations to automatically register services in the DI container.
- Prerequisites
- Setting up Annotations
- Installing AnnotationServiceBuilder
- Usage
- Trimming Safety Considerations
- ASB: Observing the Logic of Pattern Standards
- Benefits of Using AnnotationServiceBuilder
- .NET 6.0 or later
- Visual Studio 2022 (or any other IDE with .NET support)
Ensure that your .NET SDK is up-to-date. This project requires .NET 6.0 or later.
The Annotations
folder in the project contains the key attributes used for automatically registering services in the DI container. Below are the files and their purposes, along with examples of how they are used.
You can install the AnnotationServiceBuilder package via NuGet.
dotnet add package AnnotationServiceBuilder
To register your services, follow these steps:
- Initialize the
AnnotationServiceRegistrar
:
AnnotationServiceRegistrar.Initialize(Assembly.GetExecutingAssembly());
- Add your services to the DI container:
AnnotationServiceRegistrar.AddSingletonServices(services);
AnnotationServiceRegistrar.AddScopedServices(services);
AnnotationServiceRegistrar.AddTransientServices(services);
AnnotationServiceRegistrar.AddRefitClients(services, "https://api.yourservice.com"); // Replace with your API base URL
If you need to use a custom DelegatingHandler
, use the following:
var customHandler = new MyCustomHandler();
AnnotationServiceRegistrar.AddRefitClients(services, "https://api.yourservice.com", customHandler);
using AnnotationServiceBuilder.Annotations.Scoped;
[ScopedService(typeof(IMyScopedService))]
public class MyScopedService : IMyScopedService
{
// Implementation...
}
using AnnotationServiceBuilder.Annotations.Singleton;
[SingletonService]
public class MySingletonService
{
// Implementation...
}
using AnnotationServiceBuilder.Annotations.Transient;
[TransientService]
public class MyTransientService
{
// Implementation...
}
using AnnotationServiceBuilder.Annotations.Refit;
using AnnotationServiceBuilder.Data.Models;
using Refit;
namespace AnnotationServiceBuilder.Network.Repositories
{
[RefitClient]
public interface IPostsApi
{
[Get("/posts")]
Task<List<Post>> GetPostsAsync();
[Get("/posts/{id}")]
Task<Post> GetPostByIdAsync(int id);
}
}
using AnnotationServiceBuilder.Annotations.Refit;
using Refit;
namespace AnnotationServiceBuilder.Network.Repositories
{
[RefitClient(BaseUrl = "https://api.service1.com")]
public interface IService1Api
{
[Get("/endpoint1")]
Task<List<ResponseModel1>> GetService1DataAsync();
}
[RefitClient(BaseUrl = "https://api.service2.com")]
public interface IService2Api
{
[Get("/endpoint2")]
Task<List<ResponseModel2>> GetService2DataAsync();
}
[RefitClient(BaseUrl = "https://api.service3.com")]
public interface IService3Api
{
[Get("/endpoint3")]
Task<List<ResponseModel3>> GetService3DataAsync();
}
}
To ensure that your services are not trimmed during the optimization process, use the trimming-safe registration methods provided by AnnotationServiceBuilder. These methods will guarantee that necessary types are preserved and registered correctly.
AnnotationServiceRegistrar.Initialize(Assembly.GetExecutingAssembly());
AnnotationServiceRegistrar.AddSingletonServicesWithTrimmingSafety(services);
AnnotationServiceRegistrar.AddScopedServicesWithTrimmingSafety(services);
AnnotationServiceRegistrar.AddTransientServicesWithTrimmingSafety(services);
AnnotationServiceRegistrar.AddRefitClientsWithTrimmingSafety(services, "https://api.yourservice.com"); // Replace with your API base URL
If this approach doesn't help, you may try to manually apply trimming safety considerations.
using System.Diagnostics.CodeAnalysis;
[SingletonService]
public class StockPartsService
{
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(MyDependentService))]
public StockPartsService()
{
// Method implementation ensuring MyDependentService is retained
}
}
using System.Runtime.CompilerServices;
[Preserve]
[SingletonService]
public class MyDependentService
{
public void PerformOperation()
{
// Implementation that must be retained during trimming
}
}
Note: Factory patterns have been moved to a new library, AnnotationServiceBuilder.Patterns. Please update your code accordingly to use the new library. For more details, see: AnnotationServiceBuilder.Patterns.
Automatically register your services in the DI container without needing to manually add each service in Startup.cs
or Program.cs
. This reduces boilerplate code and makes your setup process much more streamlined.
Annotations define the lifetime of services (Singleton, Scoped, Transient), making your code more organized and easier to maintain.
Automating service registration saves time, especially in large projects. Developers can focus on building features instead of managing service registrations manually.
The library provides a simple, intuitive API for registering services and Refit clients, making the process user-friendly.
Registered classes and interfaces are cached to improve performance and reduce the overhead of repeated reflection operations.
For video guides on how to use AnnotationServiceBuilder, you can watch these YouTube videos:
We welcome contributions! Please submit a pull request or open an issue to discuss your ideas or report bugs.
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 Gennadii Ianchev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.