Fixes #2 by providing a proper implementation of GetServices that actually returns instances of those services instead of just a list of types.

This commit is contained in:
Samuele Lorefice
2025-09-24 04:07:24 +02:00
parent d20788de33
commit 3df2f50765
2 changed files with 16 additions and 0 deletions

View File

@@ -12,6 +12,12 @@ class Service : IService {
}
}
class AnotherService : IService {
public void Log(string message) {
Console.WriteLine($"[AnotherService] {message}");
}
}
interface IOtherService {
public Guid Id { get; }
@@ -47,6 +53,7 @@ static class Program {
static void Main(string[] args) {
var container = new ServiceContainer()
.AddSingleton<IService, Service>()
.AddTransient<IService, AnotherService>()
.AddTransient<IOtherService, GuidService>()
.AddTransient<GuidDependantService, GuidDependantService>();
@@ -55,5 +62,6 @@ static class Program {
container.GetService<IOtherService>().ShowId();
container.GetService<GuidDependantService>().LogWithId("Hello, sent from the dependency.");
container.GetService<IService>().Log("Goodbye, Dependency Injection!");
var res = container.GetServices<IService>();
}
}

View File

@@ -18,6 +18,14 @@ public class ServiceContainer {
descriptors.Where(d => d.ServiceType == typeof(TServices))
.Select(d => d.ImplementationType).ToList();
/// <summary>
/// Get all registered services for a given service type.
/// </summary>
/// <typeparam name="TService"></typeparam>
public List<TService> GetServices<TService>() where TService : class =>
descriptors.Where(d => d.ServiceType == typeof(TService))
.Select(d => (TService)GetService(d.ImplementationType)).ToList();
/// <summary>
/// Registers a singleton service with its implementation.
/// </summary>