using System; using System.Collections.Generic; using Microsoft.AspNetCore.Sockets; using Microsoft.Extensions.DependencyInjection; namespace SocketsSample { public class SocketFormatters { private IServiceProvider _serviceProvider; private Dictionary> _formatters = new Dictionary>(); private Dictionary _invocationAdapters = new Dictionary(); public SocketFormatters(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void RegisterFormatter(string format) where TFormatterType : IFormatter { Dictionary formatFormatters; if (!_formatters.TryGetValue(format, out formatFormatters)) { formatFormatters = _formatters[format] = new Dictionary(); } formatFormatters[typeof(T)] = typeof(TFormatterType); } public IFormatter GetFormatter(string format) { Dictionary formatters; Type targetFormatterType; if (_formatters.TryGetValue(format, out formatters) && formatters.TryGetValue(typeof(T), out targetFormatterType)) { return (IFormatter)_serviceProvider.GetRequiredService(targetFormatterType); } return null; // throw new InvalidOperationException($"No formatter register for format '{format}' and type '{typeof(T).GetType().FullName}'"); } public void RegisterInvocationAdapter(string format, IInvocationAdapter adapter) { _invocationAdapters[format] = adapter; } public IInvocationAdapter GetInvocationAdapter(string format) { IInvocationAdapter value; return _invocationAdapters.TryGetValue(format, out value) ? value : null; } } }