在阅读本文章以前,你能够先阅读:函数
Microsoft.Extensions.DependencyInjection是.NET Core内置依赖注入模块。this
首先,在Startup.ConfigureServices方法中,将Knife,Actor注册到服务容器中。spa
public void ConfigureServices(IServiceCollection services) { services.AddTransient<Actor>(); services.AddTransient<Knife>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Example.DependencyInjection.WebApi", Version = "v1" }); }); }
而后,增长HomeController,执行actor.Kill。调试
using Microsoft.AspNetCore.Mvc; using System; namespace Autofac.WebApi.Controllers { [Route("[controller]")] [ApiController] public class HomeController : Controller { private readonly Actor actor; public HomeController(Actor actor) { this.actor = actor ?? throw new ArgumentNullException(nameof(actor)); } [HttpGet] public string Get() { return actor.Kill(); } } }
启动调试,让咱们来看看输出结果:code
小明用刀杀怪
首先,分别建三个表明生命周期的类,MySingletonService,MyScopedService,MyTransientService。生命周期
namespace Example.DependencyInjection.WebApi { public class MySingletonService { } public class MyScopedService { } public class MyTransientService { } }
而后,在Startup.ConfigureServices方法中,将MySingletonService,MyScopedService,MyTransientService注册到服务容器中。作用域
services.AddSingleton<MySingletonService, MySingletonService>(); services.AddScoped<MyScopedService, MyScopedService>(); services.AddTransient<MyTransientService, MyTransientService>();
最后,HomeController增长GetServiceLifetime方法。string
[Route("ServiceLifetime")] [HttpGet] public List<string> GetServiceLifetime([FromServices] MySingletonService singleton1, [FromServices] MySingletonService singleton2, [FromServices] MyScopedService scoped1, [FromServices] MyScopedService scoped2, [FromServices] MyTransientService transient1, [FromServices] MyTransientService transient2) { var s = new List<string>(); s.Add($"singleton1:{singleton1.GetHashCode()}"); s.Add($"singleton2:{singleton2.GetHashCode()}"); s.Add($"scoped1:{scoped1.GetHashCode()}"); s.Add($"scoped2:{scoped2.GetHashCode()}"); s.Add($"transient1:{transient1.GetHashCode()}"); s.Add($"transient2:{transient2.GetHashCode()}"); return s; }
启动调试,执行两遍,让咱们来看看输出结果: 第一遍:it
[ "singleton1:65122748", "singleton2:65122748", "scoped1:52786977", "scoped2:52786977", "transient1:16782441", "transient2:16991442" ]
第二遍:io
[ "singleton1:65122748", "singleton2:65122748", "scoped1:56140151", "scoped2:56140151", "transient1:1997173", "transient2:54718731" ]
从结果咱们发现:
注意例子中,咱们使用经过 [FromServices] 注入的,另外咱们也能够选择经过 controller 构造函数注入,这是在 controller 中有两种依赖注入的实例的获取方式。