梦想博客

在asp.net core中使用autofac

calendar 2023/04/18
refresh-cw 2023/11/14
687字,2分钟

关于autofac 🔗

在asp.net core7 webapi中的使用方法

关于此项目:项目地址

最简单的代码如下(来源至DTCMS)

 1var builder = WebApplication.CreateBuilder(args);
 2builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(builder =>
 3{
 4	//实现层
 5	Assembly service = Assembly.Load("xxx.Service");
 6	//接口层
 7	Assembly iservice = Assembly.Load("xxx.IService");
 8	builder.RegisterAssemblyTypes(service, iservice)
 9		.Where(t => (t.FullName.EndsWith("Service")
10			|| t.FullName.EndsWith("Notify")
11			|| t.FullName.EndsWith("Execute")) && !t.IsAbstract) //类名以service结尾,且类型不能是抽象的
12		.AsImplementedInterfaces()
13		.InstancePerDependency();
14	// 从程序集中注册所有实现了IService接口的服务
15});

以上便完成了对上述两个程序集的自动注入

请注意,如上只是一个简单的示例,在不同的项目需要注入的方式不同,如果是Transient/Scoped/Singleton 需要单独配置

2023/11/14日更新 🔗

正好有项目用到了按照不同的service来配置不同的生命周期,所以来更新一下

目前看到的其他项目用到的都是以文件名结尾的,总感觉不是很优雅,所以我采用的特性来完成

首先创建一个enum和Attribute

 1	/// <summary>
 2	/// 生命周期
 3	/// </summary>
 4	public enum LifeCycle
 5	{
 6		/// <summary>
 7		/// 单例
 8		/// </summary>
 9		Singleton,
10
11		/// <summary>
12		/// 作用域
13		/// </summary>
14		Scoped,
15
16		/// <summary>
17		/// 瞬态
18		/// </summary>
19		Transient
20	}
1 public class LifeCycleAttribute : Attribute
2 {
3     public LifeCycleAttribute(LifeCycle lifeCycle)
4     {
5         LifeCycleVal = lifeCycle;
6     }
7
8     public LifeCycle LifeCycleVal { get; }
9 }

然后在Program.cs中编写如下代码

 1builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
 2     .ConfigureContainer<ContainerBuilder>(builder =>
 3     {
 4         //实现层
 5         Assembly service = Assembly.Load("GaoXinInternal.Services");
 6         //接口层
 7         Assembly iservice = Assembly.Load("GaoXinInternal.IServices");
 8         //单例
 9         builder.RegisterAssemblyTypes(service, iservice)
10            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(true)
11            .Any(attr => attr.LifeCycleVal == LifeCycle.Singleton))
12            .AsImplementedInterfaces()
13            .SingleInstance();
14
15
16         //作用域
17         builder.RegisterAssemblyTypes(service, iservice)
18            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(inherit: true)
19            .Any(attr => attr.LifeCycleVal == LifeCycle.Scoped))
20            .InstancePerLifetimeScope()
21            .AsImplementedInterfaces();
22
23         //瞬态
24         builder.RegisterAssemblyTypes(service, iservice)
25
26            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(inherit: true)
27            .Any(attr => attr.LifeCycleVal == LifeCycle.Transient))
28            .InstancePerDependency()
29            .AsImplementedInterfaces();
30     });

这里的程序集名称请按照自己项目的名称进行修改

然后在service的class上面加上特性,用于指定该类以什么生命周期进行

 1namespace GaoXinInternal.Services
 2{
 3    [LifeCycle(LifeCycle.Singleton)]
 4    public class BaseService : IBaseService
 5    {
 6        private readonly IDbConnectionFactory _connectionFactory;
 7
 8        public BaseService(IDbConnectionFactory connectionFactory)
 9        {
10            _connectionFactory = connectionFactory;
11        }
12    }
13}

以上,即可完成对autofac的自动注入

分类