.Net Core 3.x 使用Autofac替换默认Ioc容器

.net 中的IOC容器也不少,如Autofac、Windsor Castle、Spring.NET、Unity、Ninject等,现在使用Autofac作为IOC容器的较多,据说速度是最快的一个。

那么我们有必要将其应用到我们的项目中,来体验其带给我们的极速快感。

安装Autofac依赖

我们需要通过nuget包管理安装两个包:

1
2
Autofac
Autofac.Extensions.DependencyInjection

autofac

使用Autofac包

在Autofac中有多种生命周期:

  • Instance Per Dependency 对于一个服务每次请求都会返回一个唯一的实例.
  • Single Instance 所有的请求都将会返回同一个实例.
  • Instance Per Lifetime Scope 每个生命周期作用域的组件在每个嵌套的生命周期作用域中最多只会有一个单一实例
  • Instance Per Matching Lifetime Scope 每个匹配生命周期作用域的组件在每个名称匹配的嵌套生命周期作用域中最多只会有一个单一实例.
  • Instance Per Request 每个请求一个实例建立于每个匹配生命周期一个实例之上
  • Instance Per Owned Owned 隐式关系类型 创建了一个嵌套的生命周期作用域. 使用每次被拥有一个实例注册, 可以把该依赖的作用域绑定到拥有它的实例上.
  • Thread Scope 每个线程就有了它各自的生命周期作用域,在这种多线程场景中, 你必须得注意父级作用域不能在派生出的线程下被释放了

新建一个ITransientDependency空接口

1
2
3
public interface ITransientDependency
{
}

这里的主要目的是为了标识接口注册不同的声明周期。你们可以根据自己的情况新增不同的标识注入不同的生命周期

新建一个WebModule类继承Autofac的Module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class WebModule : Module
{
protected override void Load(ContainerBuilder builder)
{
//获取当前程序集
var dataAccess = Reflection.Assembly.GetExecutingAssembly();

var transientDependencyType = typeof(ITransientDependency);

//查找ITransientDependency接口类型程序并注册为每次调用创建一个实例
builder.RegisterAssemblyTypes(dataAccess)
.Where(t => transientDependencyType.IsAssignableFrom(t) && t != transientDependencyType)
.AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired();


}
}

主要是查找程序集,批量注册相应依赖,

配置使用

在Program中稍作修改

1
2
3
4
5
6
7
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

在Startup文件中加入ConfigureContainer方法:

1
2
3
4
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new WebModule());
}

至此,我们对Autofac已经配置完成

示例

接下来我们新建一个IExampleService示例接口继承ITransientDependency,

1
2
3
4
public interface IExampleService: ITransientDependency
{
string GetName(string Name);
}

新建IExampleService接口实现类:

1
2
3
4
5
6
7
public class ExampleService : IExampleService
{
public string GetName(string Name)
{
return $"My name is {Name}";
}
}

新建一个Controller,并注入IExampleService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace Web.Controllers.v1
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
IExampleService _exampleService;
public ExampleController(IExampleService exampleService)
{
_exampleService = exampleService;
}

/// <summary>
/// 查询名字
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[HttpGet]
[Route("GetName/{Name}")]
public string GetName(string Name)
{
return _exampleService.GetName(Name);
}

}
}

example
autofac_example

参考

https://autofaccn.readthedocs.io/zh/latest/
https://docs.autofac.org/en/latest/

.Net Core 3.x 使用Autofac替换默认Ioc容器

https://blogs.52fx.biz/posts/1628413452.html

作者

eyiadmin

发布于

2019-12-02

更新于

2024-05-31

许可协议

评论