- 借助依赖注入框架,可以轻松管理类之间的依赖,构建应用时遵循设计原则,确保代码的可维护性和拓展性;
ASP.NET CORE架构中,依赖注入框架提供了对象创建和生命周期管理的核心能力,各组件之间相互协作也由依赖注入框架的能力来实现。
组件包
抽象包
- Microsoft.Extensions.DependencyInjection.Abstractions
实现包
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 { } ///
}
```csharppublic class Startup{public Startup(IConfiguration configuration){Console.WriteLine("Startup");Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){Console.WriteLine("Startup.ConfigureServices");services.AddControllers();services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new OpenApiInfo { Title = "StarupDemo", Version = "v1" });});#region 注册服务不同生命周期的服务services.AddSingleton<IMySingletonService, MySingletonService>();services.AddScoped<IMyScopedService, MyScopedService>();services.AddTransient<IMyTransientService, MyTransientService>();#endregion#region 其它注册方式//直接注入实例services.AddSingleton<IMySingletonService>(new MySingletonService());//工厂模式注册services.AddSingleton<IMySingletonService>(serviceProvider =>{//可以获取其它服务组装得到最终的实现实例注入到容器中;//serviceProvider.GetService<>();return new MySingletonService();});#endregion#region 尝试注册services.AddSingleton<IMyService, MyService>();//若IMyService实例类型已注册就不会重新注册 MyServiceEx 不会重新注册services.TryAddSingleton<IMyService, MyServiceEx>();//相同类型的服务,实现类型不同可以成功注册services.TryAddEnumerable(ServiceDescriptor.Singleton<IMyService, MyServiceEx>());#endregion#region 移除和替换注册//services.Replace(ServiceDescriptor.Singleton<IOrderService, OrderServiceEx>());//services.RemoveAll<IOrderService>();#endregion#region 注册泛型模板//比如可以注册泛型仓储services.AddSingleton(typeof(IGenericService<>), typeof(GenericService<>));#endregion}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){Console.WriteLine("Startup.Configure");if (env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseSwagger();app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "StarupDemo v1"));}app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}
