在閱讀本文章以前,你能夠先閱讀:web
Autofac與C#語言的結合很是緊密,並學習它很是的簡單,也是.NET領域最爲流行的IoC框架之一。框架
首先,將Autofac的NuGet軟件包安裝到您的應用程序中。ide
Autofac
而後,咱們經過建立ContainerBuilder來註冊組件。學習
var builder = new ContainerBuilder(); builder.RegisterType<Knife>(); builder.RegisterType<Actor>();
接着,能夠經過在一個已存在的生命週期上調用 BeginLifetimeScope() 方法來建立另外一個生命週期做用域, 以根容器做爲起始。生命週期做用域是可釋放的而且追蹤組件的釋放, 所以確保你老是調用了 "Dispose()"" 或者把它們包裹在 "using" 語句內。ui
using (var scope = container.BeginLifetimeScope()) { }
最後,在註冊完組件並暴露相應的服務後, 你能夠從建立的容器或其子生命週期中解析服務. 讓咱們使用 Resolve() 方法來實現:this
using (var scope = container.BeginLifetimeScope()) { var actor = scope.Resolve<Actor>(); actor.Kill(); }
讓咱們來看看完整代碼:spa
using System; namespace Autofac.ConsoleApp { class Program { static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<Knife>(); builder.RegisterType<Actor>(); var container = builder.Build(); using (var scope = container.BeginLifetimeScope()) { var actor = scope.Resolve<Actor>(); actor.Kill(); } Console.ReadKey(); } } }
讓咱們來看看輸出結果:調試
小明用刀殺怪
首先,將Autofac,Autofac.Extensions.DependencyInjection的NuGet軟件包安裝到您的應用程序中。code
dotnet add package Autofac dotnet add package Autofac.Extensions.DependencyInjection
而後,在Program.Main中增長.UseServiceProviderFactory(new AutofacServiceProviderFactory())生命週期
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseServiceProviderFactory(new AutofacServiceProviderFactory());
接着,在Startup.ConfigureServices中增長services.AddControllersWithViews();
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Autofac.WebApi", Version = "v1" }); }); services.AddControllersWithViews(); }
接着,在Startup.ConfigureContainer方法中,將Knife,Actor註冊到Autofac中ContainerBuilder。
public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<Knife>(); builder.RegisterType<Actor>(); }
最後,增長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(); } } }
啓動調試,讓咱們來看看輸出結果:
小明用刀殺怪