ServiceMatic is an extension library designed to make Dependency Injection in .NET simpler and more powerful. The library extends IServiceCollection with a range of methods that streamline service registration, validation, and more.
Register all concrete types in a given assembly to their respective interfaces.
var services = new ServiceCollection();
services.AddServicesFromAssembly(Assembly.GetExecutingAssembly());Assembly assembly: The assembly to scan for services.Func<Type, bool> filter: A filter function to include/exclude types from registration.ServiceLifetime lifetime: The lifetime of the registered service (Transient, Scoped, Singleton).
Scan an assembly for classes with the RegisterService attribute and register them accordingly.
First, decorate your classes with RegisterService attribute:
[RegisterService(ServiceLifetime.Singleton)]
public class MySingletonService : IMySingletonService
{
// Implementation
}Then, use AddServicesWithAttribute:
var services = new ServiceCollection();
services.AddServicesWithAttribute(Assembly.GetExecutingAssembly());Assembly assembly: The assembly to scan.ServiceLifetime defaultLifetime: Default lifetime for services without a specified lifetime in the attribute.
Wrap an existing service with a decorator to extend its functionality.
services.Decorate<IMyService>((sp, myService) => new MyServiceDecorator(myService));Retrieve a graph representing the dependencies between registered services.
var graph = services.GetDependencyGraph();Get the total count of registered services in IServiceCollection.
int count = services.CountRegisteredServices();Register multiple services at once using a list of tuples, where each tuple contains a service type, its implementation, and the lifetime.
var batch = new List<(Type serviceType, Type implementationType, ServiceLifetime lifetime)>
{
(typeof(IMyService), typeof(MyService), ServiceLifetime.Transient)
};
services.AddBatchServices(batch);Validate all registered services to ensure they can be resolved.
var graph = new DependencyGraph();
services.ValidateRegistrations(graph);Register services from a JSON configuration file.
Assume a JSON (config.json) as follows:
[
{
"ServiceType": "IMyService, MyNamespace",
"ImplementationType": "MyService, MyNamespace",
"Lifetime": "Transient"
}
]Load this into your services collection like this:
services.AddServicesFromConfiguration("path/to/config.json", graph);Remove services from IServiceCollection based on a predicate function.
services.RemoveServices(descriptor => descriptor.ServiceType == typeof(IMyService));