~ruther/NosSmooth.Comms

ref: 12e8d20913473e4c044e11e9460fd0c7b7bb3d0c NosSmooth.Comms/src/Core/NosSmooth.Comms.Core/Extensions/ServiceCollectionExtensions.cs -rw-r--r-- 6.8 KiB
12e8d209 — Rutherther feat: add a console sample logging all received and sent packets from nostale process 2 years ago
                                                                                
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//
//  ServiceCollectionExtensions.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.DependencyInjection;
using NosSmooth.Comms.Core.Responders;
using NosSmooth.Comms.Data;
using NosSmooth.Comms.Data.Responders;
using NosSmooth.Core.Client;

namespace NosSmooth.Comms.Core.Extensions;

/// <summary>
/// Extension methods for <see cref="IServiceCollection"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Adds server handling (<see cref="MessageHandler"/> and <see cref="ServerManager"/>).
    /// </summary>
    /// <remarks>
    /// The specific server has to be added separately as <see cref="IServer"/>.
    /// </remarks>
    /// <param name="serviceCollection">The service collection.</param>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddServerHandling(this IServiceCollection serviceCollection)
        => serviceCollection
            .AddNosSmoothResolverOptions()
            .AddSingleton<MessageHandler>(p => new MessageHandler(p, true))
            .AddSingleton<ServerManager>()
            .AddInjecting();

    /// <summary>
    /// Adds handling for a single client.
    /// </summary>
    /// <remarks>
    /// The specific client has to be added separately as <see cref="IConnection"/>.
    /// </remarks>
    /// <param name="serviceCollection">The service collection.</param>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddSingleClientHandling(this IServiceCollection serviceCollection)
        => serviceCollection
            .AddInjecting()
            .AddNosSmoothResolverOptions()
            .AddMessageResponder<ResponseResultResponder>()
            .AddSingleton<NostaleClientResolver>()
            .AddSingleton<IConnection>(p => p.GetRequiredService<IClient>())
            .AddSingleton<MessageHandler>(p => new MessageHandler(p, false))
            .AddScoped<ConnectionHandler>()
            .AddScoped<INostaleClient, ClientNostaleClient>();

    /// <summary>
    /// Add handling for multiple clients.
    /// </summary>
    /// <remarks>
    /// The clients should not be inside of the provider.
    /// Initialize clients outside of the provider and use the
    /// provider for injecting connection handler and nostale client.
    /// Nostale client will be created automatically if connection is injected successfully.
    /// Connection will be injected when calling message handler with the specific connection.
    ///
    /// Connection may be injected by setting <see cref="ConnectionInjector"/> properties in a scope.
    /// </remarks>
    /// <param name="serviceCollection">The service collection.</param>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddMultiClientHandling(this IServiceCollection serviceCollection)
        => serviceCollection
            .AddNosSmoothResolverOptions()
            .AddSingleton<NostaleClientResolver>()
            .AddSingleton<MessageHandler>(p => new MessageHandler(p, false))
            .AddInjecting()
            .AddScoped<INostaleClient>
                (p => p.GetRequiredService<NostaleClientResolver>().Resolve(p.GetRequiredService<ConnectionHandler>()));

    /// <summary>
    /// Add <see cref="NosSmoothMessageSerializerOptions"/> with default NosSmooth options.
    /// </summary>
    /// <param name="serviceCollection">The service collection.</param>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddNosSmoothResolverOptions(this IServiceCollection serviceCollection)
        => serviceCollection
            .Configure<NosSmoothMessageSerializerOptions>
                (o => o.Options = o.Options.WithResolver(NosSmoothResolver.Instance));

    /// <summary>
    /// Adds a message responder.
    /// </summary>
    /// <param name="serviceCollection">The service collection.</param>
    /// <typeparam name="TResponder">The type of the responder.</typeparam>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddMessageResponder<TResponder>(this IServiceCollection serviceCollection)
    {
        return serviceCollection.AddMessageResponder(typeof(TResponder));
    }

    /// <summary>
    /// Adds a message responder.
    /// </summary>
    /// <param name="serviceCollection">The service collection.</param>
    /// <param name="responderType">The type of the responder.</param>
    /// <returns>The same service collection.</returns>
    public static IServiceCollection AddMessageResponder(this IServiceCollection serviceCollection, Type responderType)
    {
        if (serviceCollection.Any(x => x.ImplementationType == responderType))
        { // already added... assuming every packet responder was added even though that may not be the case.
            return serviceCollection;
        }

        if (!responderType.GetInterfaces().Any
            (
                i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMessageResponder<>)
            ))
        {
            throw new ArgumentException
            (
                $"{nameof(responderType)} should implement IMessageResponder.",
                nameof(responderType)
            );
        }

        var responderTypeInterfaces = responderType.GetInterfaces();
        var responderInterfaces = responderTypeInterfaces.Where
        (
            r => r.IsGenericType && r.GetGenericTypeDefinition() == typeof(IMessageResponder<>)
        );

        foreach (var responderInterface in responderInterfaces)
        {
            serviceCollection.AddScoped(responderInterface, responderType);
        }

        return serviceCollection;
    }

    private static IServiceCollection AddInjecting(this IServiceCollection serviceCollection)
        => serviceCollection
            .AddScoped<ConnectionInjector>()
            .AddScoped<ConnectionHandler>
            (
                p =>
                {
                    var handler = p.GetRequiredService<ConnectionInjector>().ConnectionHandler;
                    if (handler is null)
                    {
                        throw new InvalidOperationException("Connection handler was requested, but is not injected.");
                    }

                    return handler;
                }
            )
            .AddScoped<IConnection>
            (
                p =>
                {
                    var connection = p.GetRequiredService<ConnectionInjector>().Connection;
                    if (connection is null)
                    {
                        throw new InvalidOperationException("Connection was requested, but is not injected.");
                    }

                    return connection;
                }
            );
}
Do not follow this link