梦想博客

在asp.net core中使用autofac

· 598 words · 2 minutes to read

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

关于此项目:项目地址

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

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

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

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

2023/11/14日更新 🔗

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

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

首先创建一个enum和Attribute

	/// <summary>
	/// 生命周期
	/// </summary>
	public enum LifeCycle
	{
		/// <summary>
		/// 单例
		/// </summary>
		Singleton,

		/// <summary>
		/// 作用域
		/// </summary>
		Scoped,

		/// <summary>
		/// 瞬态
		/// </summary>
		Transient
	}
 public class LifeCycleAttribute : Attribute
 {
     public LifeCycleAttribute(LifeCycle lifeCycle)
     {
         LifeCycleVal = lifeCycle;
     }

     public LifeCycle LifeCycleVal { get; }
 }

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

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
     .ConfigureContainer<ContainerBuilder>(builder =>
     {
         //实现层
         Assembly service = Assembly.Load("GaoXinInternal.Services");
         //接口层
         Assembly iservice = Assembly.Load("GaoXinInternal.IServices");
         //单例
         builder.RegisterAssemblyTypes(service, iservice)
            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(true)
            .Any(attr => attr.LifeCycleVal == LifeCycle.Singleton))
            .AsImplementedInterfaces()
            .SingleInstance();


         //作用域
         builder.RegisterAssemblyTypes(service, iservice)
            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(inherit: true)
            .Any(attr => attr.LifeCycleVal == LifeCycle.Scoped))
            .InstancePerLifetimeScope()
            .AsImplementedInterfaces();

         //瞬态
         builder.RegisterAssemblyTypes(service, iservice)

            .Where(t => t.GetCustomAttributes<LifeCycleAttribute>(inherit: true)
            .Any(attr => attr.LifeCycleVal == LifeCycle.Transient))
            .InstancePerDependency()
            .AsImplementedInterfaces();
     });

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

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

namespace GaoXinInternal.Services
{
    [LifeCycle(LifeCycle.Singleton)]
    public class BaseService : IBaseService
    {
        private readonly IDbConnectionFactory _connectionFactory;

        public BaseService(IDbConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
        }
    }
}

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

Categories