HandlerFactory.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Logging;
  6. namespace BubbleSocketCore.Handlers
  7. {
  8. class HandlerFactory
  9. {
  10. private static List<IHandler> handlers = new List<IHandler>();
  11. private readonly IConfiguration Configuration;
  12. private readonly ILoggerFactory LoggerFactory;
  13. private readonly ILogger Logger;
  14. public HandlerFactory(IConfiguration configuration, ILoggerFactory loggerFactory)
  15. {
  16. Configuration = configuration;
  17. LoggerFactory = loggerFactory;
  18. Logger = LoggerFactory.CreateLogger("HandlerFactory");
  19. handlers.Add(new DummyHandler());
  20. handlers.Add(new EchoHandler());
  21. handlers.Add(new PlayerConnectionHandler(Configuration, LoggerFactory));
  22. }
  23. internal IHandler Get(HttpRequest request)
  24. {
  25. foreach (var handler in handlers)
  26. {
  27. if (handler.IsListening(request))
  28. {
  29. return handler;
  30. }
  31. }
  32. throw new HandlerNotFoundException($"{request.Scheme}://{request.Host}{request.Path}");
  33. }
  34. }
  35. class HandlerNotFoundException : Exception
  36. {
  37. public HandlerNotFoundException(string message) : base(message)
  38. {
  39. }
  40. }
  41. }