当前位置:网站首页>Autofac注册组件(3)
Autofac注册组件(3)
2022-07-18 04:29:00 【有诗亦有远方】
Autofac注册组件
官网地址
一、扫描类型
在其他方面,被称为约定驱动的注册或扫描,Autofac可以根据用户指定的规则从一个程序集中注册一组类型:
builder.RegisterAssemblyTypes(typeof(BaseRepository<>).Assembly)
RegisterAssemblyTypes()
调用将适用一组规则,如果有多种不同的组件注册,一次或多次调用
1.过滤类型(Filtering Types)
RegisterAssemblyTypes()接受一个或多个程序集的参数数组。默认情况下,程序集中的所有的公共的,具体类将被注册。你可以过滤一组注册的类型,通过使用linq表达式。
过滤注册类型,使用Where()语法过滤:
builder.RegisterAssemblyTypes(typeof(IService).Assembly)
//IsAssignableFrom 判断IService类型是否与X类型一样
.Where(x => typeof(IService).IsAssignableFrom(x))
// 是以接口方式进行注入,注入这些类的所有的公共接口作为服务(除了释放资源)
.AsImplementedInterfaces().InstancePerLifetimeScope();
2.指定服务(Specifying Services)
对于RegisterAssemblyTypes()注册语法是单个类型注册语法的超级集合,所以像As()方法都将在程序集中很好的工作
builder.Register().As<>().InstancePerLifetimeScope();
正如通常的组件注册,可以一起添加多个As()调用。
还添加了一些额外的注册方法,使其更容易建立共同的约定:
方法 | 描述 | 示例 |
---|---|---|
AsImplementedInterfaces() | 注册类型提供所有其公共接口作为服务(不包括IDisposable接口)。 | builder.RegisterAssemblyTypes(asm).Where(t => t.Name.EndsWith(“Repository”)).AsImplementedInterfaces(); |
AsClosedTypesOf(open) | 可分配给注册类型一个接近开放泛型类型的实例。 | builder.RegisterAssemblyTypes(asm).AsClosedTypesOf(typeof(IRepository<>)); |
AsSelf() | 默认: 注册类型本身 - 当重写其他服务默认规范时非常有用。 | builder.RegisterAssemblyTypes(asm) .AsImplementedInterfaces().AsSelf(); |
二、net core 3.x使用Autofac以及使用Autofac进行自动注入
一、需要引入的库:
Autofac
Autofac.Extensions.DependencyInjection
二、使用Autofac工厂
Program.cs中添加:.UseServiceProviderFactory(new AutofacServiceProviderFactory())
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>(); })
.UseServiceProviderFactory(new AutofacServiceProviderFactory());
三、StarpUp.cs中添加方法
public virtual void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new ApplicationModule(Configuration[ApiDefaults.ConnectionString]));
builder.RegisterModule(new MediatorModule());
}
四、设置注册类型模块
/// 自动注入通过继承Module
public class ApplicationModule : Module
{
//重写load方法用于加载配置
protected override void Load(ContainerBuilder moduleBuilder)
{
var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray();
var perRequestType = typeof(IScoped);
moduleBuilder.RegisterAssemblyTypes(assemblys)
.Where(t => perRequestType.IsAssignableFrom(t) && t != perRequestType)
.PropertiesAutowired()
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
var perDependencyType = typeof(ITransient);
moduleBuilder.RegisterAssemblyTypes(assemblys)
.Where(t => perDependencyType.IsAssignableFrom(t) && t != perDependencyType)
.PropertiesAutowired()
.AsImplementedInterfaces()
.InstancePerDependency();
var singleInstanceType = typeof(ISingleton);
moduleBuilder.RegisterAssemblyTypes(assemblys)
.Where(t => singleInstanceType.IsAssignableFrom(t) && t != singleInstanceType)
.PropertiesAutowired()
.AsImplementedInterfaces()
.SingleInstance();
}
}
以上 ITransient、ISingleton、IScoped分别是代表三个生命周期的接口
边栏推荐
- Software testing weekly (issue 80): when the words you want to talk have surged to the tip of your tongue, but the moment you hold those words back, from that moment on, you become an adult.
- FL Studio20.9水果个人工作室必备DAW编曲制作
- 【FPGA教程案例28】基于FPGA的DDS直接数字频率合成器之一——原理介绍
- LeetCode 6121. Query the number with the smallest k after cutting the number
- WPF---设计一个简单的“在线教育系统”界面
- [Luogu] p3901 sequence to find a difference
- Composition and drawing of box diagram - detailed explanation
- AutoJs学习-实现图片剪切
- Notes on the combined use of ftxui keys and ros2 cli (turnlesim+teleop)
- Golang signal.Notify 信号的退出
猜你喜欢
Difference between temporary and permanent cases of Nacos and health examination mechanism
Ftxui basic notes (botton button component advanced)
FTXUI基础笔记(botton按钮组件进阶)
请问mysql 如何取每组前三条
LeetCode 6121. 裁剪数字后查询第 K 小的数字
『ScheduleMaster』快速上手.NET Core下的开源分布式任务调度平台
PYQT5-天气预报的案例
Enterprise architecture is the "site skill" of Engineering Students
[fisheye camera model] understanding of fisheye camera projection model
嵌入式系统中实时性分析与实时性提升方案
随机推荐
Real time analysis and real-time improvement scheme in embedded system
Canvas线条粒子动画
【CVPR2020】RandLA-Net:大规模点云的高效语义分割
ML:LIME/SP-LIME的简介、原理、使用方法、经典案例之详细攻略
The st experience effect of cloud (referred to as om file for short), users insist on changing
Difference between temporary and permanent cases of Nacos and health examination mechanism
AI常用框架和工具丨12. 深度学习框架PyTorch
树莓派设置静态IP
flutter自用样式模板
PCB线宽与电阻的计算
『PostgreSQL』PGSQL手动创建Sequence序列
LeetCode 6121. Query the number with the smallest k after cutting the number
SVD singular decomposition applied to image compression
[转载] GPU Compute Capability表
Electron常见问题 61 - 客户端必须以管理员权限运行?
Flask template
CompletableFuture异步编排
连接云服务器Docker中的Mysql 详细图文操作(全)
【FPGA教程案例28】基于FPGA的DDS直接数字频率合成器之一——原理介绍
Which securities company is good for opening an account for buying stocks by mobile phone? Which is safer