net core依赖注入
.NetCore中依赖注入有几个关键的类型,简单介绍一下:
IServiceCollection:负责存储注册的服务,可以通过其扩展方法进行服务注册;
ServiceDescriptor:服务注册时的信息,如服务类型、实现类型、实例类型、生命周期等;
IServiceProvider: 理解是常说的容器,是IServiceCollection创建出来的,用来提供实例的;
IServiceScope:表示一个容器的子容器的生命周期;
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // builder.Services.IsReadOnly = false; builder.Services.AddScoped<IFoo,Foo>(); using (IServiceScope scope = builder.Services.BuildServiceProvider().CreateScope()) { var foo = scope.ServiceProvider.GetService<IFoo>(); foo.Show(); } // 依赖注入的东西要放到Build之前。 var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.MapGet("/2", () => "Hello World!"); app.Run();
背景:net 7.
public interface IFoo{ public void Show(); } public class Foo : IFoo{ public void Show(){ System.Console.WriteLine("hello Foo"); } }