• 借助依赖注入框架,可以轻松管理类之间的依赖,构建应用时遵循设计原则,确保代码的可维护性和拓展性;
  • ASP.NET CORE架构中,依赖注入框架提供了对象创建和生命周期管理的核心能力,各组件之间相互协作也由依赖注入框架的能力来实现。

    组件包

  • 抽象包

    • Microsoft.Extensions.DependencyInjection.Abstractions
  • 实现包

    • Microsoft.Extensions.DependencyInjection

      核心类型

  • IServiceCollection

    • 负责服务注册
  • ServiceDescriptor
    • 包含每个服务注册时的信息
  • IServiceProvider
    • 具体服务容器,由ServiceCollection builder出来
  • IServiceScope

    • 表示容器生命周期

      生命周期

  • Singleton(单例)

    • 全局单例
  • Scoped(作用域)
    • 范围单例
  • Transient(瞬时/暂时) ```csharp /// /// 瞬时 /// public interface IMyTransientService { } public class MyTransientService : IMyTransientService { } /// /// 单例 /// public interface IMySingletonService { } public class MySingletonService : IMySingletonService { } /// /// 作用域 /// public interface IMyScopedService { } public class MyScopedService : IMyScopedService { }

public interface IMyService { } public class MyService : IMyService { } public class MyServiceEx : IMyService { } ///

/// 泛型 /// public interface IGenericService { } public class GenericService : IGenericService { public T Data { get; private set; } public GenericService(T data) { this.Data = data; }

}

  1. ```csharp
  2. public class Startup
  3. {
  4. public Startup(IConfiguration configuration)
  5. {
  6. Console.WriteLine("Startup");
  7. Configuration = configuration;
  8. }
  9. public IConfiguration Configuration { get; }
  10. // This method gets called by the runtime. Use this method to add services to the container.
  11. public void ConfigureServices(IServiceCollection services)
  12. {
  13. Console.WriteLine("Startup.ConfigureServices");
  14. services.AddControllers();
  15. services.AddSwaggerGen(c =>
  16. {
  17. c.SwaggerDoc("v1", new OpenApiInfo { Title = "StarupDemo", Version = "v1" });
  18. });
  19. #region 注册服务不同生命周期的服务
  20. services.AddSingleton<IMySingletonService, MySingletonService>();
  21. services.AddScoped<IMyScopedService, MyScopedService>();
  22. services.AddTransient<IMyTransientService, MyTransientService>();
  23. #endregion
  24. #region 其它注册方式
  25. //直接注入实例
  26. services.AddSingleton<IMySingletonService>(new MySingletonService());
  27. //工厂模式注册
  28. services.AddSingleton<IMySingletonService>(serviceProvider =>
  29. {
  30. //可以获取其它服务组装得到最终的实现实例注入到容器中;
  31. //serviceProvider.GetService<>();
  32. return new MySingletonService();
  33. });
  34. #endregion
  35. #region 尝试注册
  36. services.AddSingleton<IMyService, MyService>();
  37. //若IMyService实例类型已注册就不会重新注册 MyServiceEx 不会重新注册
  38. services.TryAddSingleton<IMyService, MyServiceEx>();
  39. //相同类型的服务,实现类型不同可以成功注册
  40. services.TryAddEnumerable(ServiceDescriptor.Singleton<IMyService, MyServiceEx>());
  41. #endregion
  42. #region 移除和替换注册
  43. //services.Replace(ServiceDescriptor.Singleton<IOrderService, OrderServiceEx>());
  44. //services.RemoveAll<IOrderService>();
  45. #endregion
  46. #region 注册泛型模板
  47. //比如可以注册泛型仓储
  48. services.AddSingleton(typeof(IGenericService<>), typeof(GenericService<>));
  49. #endregion
  50. }
  51. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  52. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  53. {
  54. Console.WriteLine("Startup.Configure");
  55. if (env.IsDevelopment())
  56. {
  57. app.UseDeveloperExceptionPage();
  58. app.UseSwagger();
  59. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "StarupDemo v1"));
  60. }
  61. app.UseRouting();
  62. app.UseAuthorization();
  63. app.UseEndpoints(endpoints =>
  64. {
  65. endpoints.MapControllers();
  66. });
  67. }
  68. }