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:
@@ -12,6 +12,12 @@ class Service : IService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class AnotherService : IService {
|
||||||
|
public void Log(string message) {
|
||||||
|
Console.WriteLine($"[AnotherService] {message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
interface IOtherService {
|
interface IOtherService {
|
||||||
public Guid Id { get; }
|
public Guid Id { get; }
|
||||||
|
|
||||||
@@ -47,6 +53,7 @@ static class Program {
|
|||||||
static void Main(string[] args) {
|
static void Main(string[] args) {
|
||||||
var container = new ServiceContainer()
|
var container = new ServiceContainer()
|
||||||
.AddSingleton<IService, Service>()
|
.AddSingleton<IService, Service>()
|
||||||
|
.AddTransient<IService, AnotherService>()
|
||||||
.AddTransient<IOtherService, GuidService>()
|
.AddTransient<IOtherService, GuidService>()
|
||||||
.AddTransient<GuidDependantService, GuidDependantService>();
|
.AddTransient<GuidDependantService, GuidDependantService>();
|
||||||
|
|
||||||
@@ -55,5 +62,6 @@ static class Program {
|
|||||||
container.GetService<IOtherService>().ShowId();
|
container.GetService<IOtherService>().ShowId();
|
||||||
container.GetService<GuidDependantService>().LogWithId("Hello, sent from the dependency.");
|
container.GetService<GuidDependantService>().LogWithId("Hello, sent from the dependency.");
|
||||||
container.GetService<IService>().Log("Goodbye, Dependency Injection!");
|
container.GetService<IService>().Log("Goodbye, Dependency Injection!");
|
||||||
|
var res = container.GetServices<IService>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,6 +18,14 @@ public class ServiceContainer {
|
|||||||
descriptors.Where(d => d.ServiceType == typeof(TServices))
|
descriptors.Where(d => d.ServiceType == typeof(TServices))
|
||||||
.Select(d => d.ImplementationType).ToList();
|
.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>
|
/// <summary>
|
||||||
/// Registers a singleton service with its implementation.
|
/// Registers a singleton service with its implementation.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
Reference in New Issue
Block a user