ASP.NET Core中如影随形的”依赖注入”[上]: 从两个不同的ServiceProvider说起

   1: public class Program

   2: {

   3:     public static void Main()

   4:     {

   5:         new WebHostBuilder()

   6:             .ConfigureLogging(loggerFactory=>loggerFactory.AddConsole())

   7:             .UseKestrel()

   8:             .ConfigureServices(svcs=>svcs

   9:                 .AddSingleton<IFoo, Foo>()

  10:                 .AddScoped<IBar, Bar>()

  11:                 .AddTransient<IBaz, Baz>())

  12:             .Configure(app => app.Run(async context =>{

  13:                 context.RequestServices.GetService<IFoo>();

  14:                 context.RequestServices.GetService<IBar>();

  15:                 context.RequestServices.GetService<IBaz>();

  16:                 await context.Response.WriteAsync("End");

  17:             }))

  18:             .Build()

  19:             .Run();

  20:     } 

  21: }

  22:  

  23: public interface IFoo {}

  24: public interface IBar {}

  25: public interface IBaz {}

  26: public class ServiceBase : IDisposable

  27: {

  28:     public void Dispose()

  29:     {

  30:         Console.WriteLine($"{this.GetType().Name}.Dispose()...");

  31:     }

  32: }

  33: public class Foo : ServiceBase, IFoo {}

  34: public class Bar : ServiceBase, IBar {}

  35: public class Baz : ServiceBase, IBaz {}