Autofac一个优秀的.NET IoC框架

南荣相如谈编程 2021-01-14 18:55:30
框架 AutoFac Ioc 一个 优秀


1 前置阅读

在阅读本文章之前,你可以先阅读:

  • 什么是依赖注入

2 简介

Autofac与C#语言的结合非常紧密,并学习它非常的简单,也是.NET领域最为流行的IoC框架之一。

3 使用

首先,将Autofac的NuGet软件包安装到您的应用程序中。

Autofac

然后,我们通过创建ContainerBuilder来注册组件。

var builder = new ContainerBuilder();
builder.RegisterType<Knife>();
builder.RegisterType<Actor>();

接着,可以通过在一个已存在的生命周期上调用 BeginLifetimeScope() 方法来创建另一个生命周期作用域, 以根容器作为起始。生命周期作用域是可释放的并且追踪组件的释放, 因此确保你总是调用了 "Dispose()"" 或者把它们包裹在 "using" 语句内。

using (var scope = container.BeginLifetimeScope())
{
}

最后,在注册完组件并暴露相应的服务后, 你可以从创建的容器或其子生命周期中解析服务. 让我们使用 Resolve() 方法来实现:

using (var scope = container.BeginLifetimeScope())
{
var actor = scope.Resolve<Actor>();
actor.Kill();
}

让我们来看看完整代码:

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();
}
}
}

让我们来看看输出结果:

小明用刀杀怪

4 在 Asp.Net Core 中使用

首先,将Autofac,Autofac.Extensions.DependencyInjection的NuGet软件包安装到您的应用程序中。

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();
}
}
}

启动调试,让我们来看看输出结果:

小明用刀杀怪
版权声明
本文为[南荣相如谈编程]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/zcqiand/p/14257650.html

  1. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  2. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  3. Learn java base conversion supplementary learning
  4. JDBC测试连接数据库
  5. JDBC test connection database
  6. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  7. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  8. 安卓开发和java开发有什么区别!2021年BATJ30套大厂Android经典高频面试题,面试必问
  9. Spring Security OAuth2.0認證授權四:分散式系統認證授權
  10. What's the difference between Android development and java development! 2021 batj30 Android classic high frequency interview questions
  11. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  12. Java微服务 vs Go微服务,究竟谁更强!?
  13. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  14. Who is stronger, Java microservice vs go microservice!?
  15. Java微服务 vs Go微服务,究竟谁更强!?
  16. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  17. Who is stronger, Java microservice vs go microservice!?
  18. springboot异常处理之404
  19. Spring boot exception handling 404
  20. Spring Boot Security 国际化 多语言 i18n 趟过巨坑
  21. springboot异常处理之404
  22. Spring boot security international multilingual I18N
  23. Spring boot exception handling 404
  24. Netty系列化之Google Protobuf编解码
  25. Netty之编解码
  26. Java编解码
  27. Netty解码器
  28. Netty与TCP粘包拆包
  29. Netty开发入门
  30. Java集合遍历时遇到的坑
  31. Spring IOC 源码解析(下)
  32. Spring IoC源码解析(上)
  33. Google protobuf codec of netty serialization
  34. Encoding and decoding of netty
  35. Java codec
  36. Netty decoder
  37. Netty and TCP packet sticking and unpacking
  38. Introduction to netty development
  39. Problems encountered in Java collection traversal
  40. Spring IOC source code analysis (2)
  41. Spring IOC source code analysis (Part one)
  42. 半小时用Spring Boot注解实现Redis分布式锁
  43. Implementing redis distributed lock with spring boot annotation in half an hour
  44. What should we do if we can't get tickets for Spring Festival transportation? You can solve this problem by using these ticket grabbing apps!
  45. 百度智能(文本识别),API传图OC代码与SDK使用
  46. springboot源码解析-管中窥豹系列之aware(六)
  47. Baidu intelligent (text recognition), API map, OC code and SDK
  48. Spring boot source code analysis
  49. springboot源码解析-管中窥豹系列之aware(六)
  50. 百度智能(文本识别),API传图OC代码与SDK使用
  51. Spring boot source code analysis
  52. Baidu intelligent (text recognition), API map, OC code and SDK
  53. Java学习笔记
  54. Java learning notes
  55. Sentry(v20.12.1) K8S 雲原生架構探索, SENTRY FOR JAVASCRIPT 手動捕獲事件基本用法
  56. 我的程式設計師之路:自學Java篇
  57. SpringBoot專案,如何優雅的把介面引數中的空白值替換為null值?
  58. Sentry (v20.12.1) k8s cloud native architecture exploration, sentry for JavaScript manual capture event basic usage
  59. My way of programmer: self study java
  60. Spring boot project, how to gracefully replace the blank value in the interface argument with null value?