This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
forked from dotnet/dotNext
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServiceProviderFactory.Builder.cs
52 lines (46 loc) · 1.87 KB
/
ServiceProviderFactory.Builder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
namespace DotNext
{
public partial class ServiceProviderFactory
{
/// <summary>
/// Represents builder of the service provider.
/// </summary>
public sealed class Builder : ISupplier<IServiceProvider>
{
private readonly IDictionary<Type, object?> services = new Dictionary<Type, object?>();
/// <summary>
/// Registers service of the specified type.
/// </summary>
/// <remarks>
/// This builder doesn't allow registration of multiple services of the same type.
/// </remarks>
/// <param name="service">The service instance.</param>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns>This builder for subsequent calls.</returns>
public Builder Add<TService>(TService service)
{
services.Add(typeof(TService), service);
return this;
}
/// <summary>
/// Constructs service provider.
/// </summary>
/// <param name="fallback">The fallback provider used for service resolution.</param>
/// <returns>The constructed service provider.</returns>
public IServiceProvider Build(IServiceProvider? fallback = null)
{
if (services.Count == 0)
return fallback ?? Empty;
return new CachedServiceProvider(services, fallback);
}
/// <summary>
/// Clears internal state of this builder and makes it reusable for subsequent calls.
/// </summary>
public void Clear() => services.Clear();
/// <inheritdoc />
IServiceProvider ISupplier<IServiceProvider>.Invoke() => Build();
}
}
}