Program.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. using System;
  4. using Microsoft.AspNetCore;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.Extensions.DependencyInjection;
  9. namespace CreateDefaultBuilderApp;
  10. public class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. WebHost.CreateDefaultBuilder()
  15. .UseUrls("http://127.0.0.1:0")
  16. .ConfigureServices((context, services) =>
  17. {
  18. services.AddSingleton(typeof(IService<>), typeof(Service<>));
  19. services.AddScoped<IAnotherService, AnotherService>();
  20. })
  21. .Configure(app =>
  22. {
  23. app.Run(context =>
  24. {
  25. try
  26. {
  27. context.RequestServices.GetService<IService<IAnotherService>>();
  28. return context.Response.WriteAsync("Success");
  29. }
  30. catch (Exception ex)
  31. {
  32. return context.Response.WriteAsync(ex.ToString());
  33. }
  34. });
  35. })
  36. .Build().Run();
  37. }
  38. interface IService<T>
  39. {
  40. }
  41. interface IAnotherService
  42. {
  43. }
  44. class Service<T> : IService<T>
  45. {
  46. public Service(T t)
  47. {
  48. }
  49. }
  50. class AnotherService : IAnotherService
  51. {
  52. }
  53. }