WogwonSociety.ServiceLocator is a lightweight and flexible service locator for .NET that simplifies dependency management in your applications. With support for multiple lifetimes, named and tagged services, constructor injection, and scoped resolution, this service locator is easy to use and helps manage complex service dependencies efficiently.
- Service Lifetime Control: Register services as Singleton or Transient.
- Named and Tagged Services: Easily register and resolve services by name or tag.
- Lazy Registration: Services can be registered lazily and resolved only when needed.
- Constructor Injection: Automatically resolves and injects constructor dependencies.
- Scoped Resolutions: Create scoped instances with service overrides.
- Fluent API: Chainable method calls for easy registration.
Install the package via NuGet:
dotnet add package WogwonSociety.ServiceLocator
- Register services with the service locator:
var locator = new ServiceLocator();
// Register singleton service
locator.Register(() => new MyService(), ServiceLifetime.Singleton);
// Register transient service
locator.Register(() => new MyService(), ServiceLifetime.Transient);
- Resolve services:
// Resolve service
var service = locator.Get<MyService>();
- Named services:
locator.Register(() => new MyService(), name: "SpecialService");
var namedService = locator.Get<MyService>("SpecialService");
- Scoped Resolution:
var scopedLocator = locator.CreateScope(new Dictionary<Type, Func<object>>
{
{ typeof(MyService), () => new ScopedService() }
});
var scopedService = scopedLocator.Get<MyService>();
- Lazy Registration:
locator.RegisterLazy(() => new ExpensiveService());
var service = locator.Get<ExpensiveService>(); // Created on first resolve
- Tagged Services:
locator.Register(() => new MyService(), tags: new[] { "tag1", "tag2" });
var service = locator.Get<MyService>("tag1");
- Resetting the Service Locator:
locator.Reset();
This project is licensed under the MIT License