.Net6 使用Autofac进行依赖注入

一、背景

刚接触.net 6,记录一下在.net6上是怎么使用Autofac进行动态的依赖注入的

二、注入方式

1、新建一个webapi项目,框架选择net 6

2、引用Nuget包---Autofac.Extensions.Dependency

3、在Program.cs上添加如下代码

cs 复制代码
//依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())//注册服务工厂
.ConfigureContainer<ContainerBuilder>(container =>
{  //添加依赖注入,AddModule是一个自定义的拓展方法,将依赖注入的方法单独提取出来,方便管理
    builder.Services.AddModule(container);
});
cs 复制代码
public static IServiceCollection AddModule(this IServiceCollection services, ContainerBuilder builder, IConfiguration configuration)
        {
	
            //初始化配置文件
            Type baseType = typeof(IDependency);//自定义的空类
            //动态运行项目的类库
            var compilationLibrary = DependencyContext.Default
                .RuntimeLibraries
                .Where(x => !x.Serviceable
                && x.Type == "project")
                .ToList();
            var count1 = compilationLibrary.Count;
            List<Assembly> assemblyList = new List<Assembly>();

            foreach (var _compilation in compilationLibrary)
            {
                try
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(_compilation.Name + ex.Message);
                }
            }
            //注册程序集的方式添加依赖
            builder.RegisterAssemblyTypes(assemblyList.ToArray())
             .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)//过滤非抽象类,继承了IDependency接口的类
             .AsSelf().AsImplementedInterfaces()
             .InstancePerLifetimeScope();//实例的生命周期
            
            //单独注册依赖服务
			//注册数据库基础操作和工作单元
			builder.RegisterGeneric(typeof(BaseRepository<,>)).As(typeof(IRepository<,>));
			builder.RegisterGeneric(typeof(UnitWork<>)).As(typeof(IUnitWork<>));
			 //注册app层
			 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
			
			 builder.RegisterType(typeof(RedisCacheContext)).As(typeof(ICacheContext));
			 
			 
			 
             builder.RegisterType<MemoryCacheService>().As<ICacheService>().SingleInstance();
            
            return services;
        }

cs 复制代码
//依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())

以及再startup.cs中添加ConfigureContainer方法

public void ConfigureContainer(ContainerBuilder builder)

{

ExtAutofac.InitAutofac(builder);

}

在app层

cs 复制代码
namespace App
{
    public static  class ExtAutofac
    {
        private static IContainer _container;
   
        public static void InitAutofac(ContainerBuilder builder)
        {
            
            //注册数据库基础操作和工作单元
            builder.RegisterGeneric(typeof(BaseRepository<,>)).As(typeof(IRepository<,>));
            builder.RegisterGeneric(typeof(UnitWork<>)).As(typeof(IUnitWork<>));

            
            //注册app层
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
            
            builder.RegisterType(typeof(RedisCacheContext)).As(typeof(ICacheContext));
            builder.RegisterType(typeof(HttpContextAccessor)).As(typeof(IHttpContextAccessor));
            
            InitDependency(builder);

        }


        /// <summary>
        /// 注入所有继承了IDependency接口
        /// </summary>
        /// <param name="builder"></param>
        private static void InitDependency(ContainerBuilder builder)
        {
            Type baseType = typeof(IDependency);
            var compilationLibrary = DependencyContext.Default
                .CompileLibraries
                .Where(x => !x.Serviceable
                            && x.Type == "project")
                .ToList();
            var count1 = compilationLibrary.Count;
            List<Assembly> assemblyList = new List<Assembly>();

            foreach (var _compilation in compilationLibrary)
            {
                try
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(_compilation.Name + ex.Message);
                }
            }
            
            builder.RegisterAssemblyTypes(assemblyList.ToArray())
                .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
                .AsSelf().AsImplementedInterfaces()
                .InstancePerLifetimeScope();
        }
    }
}
相关推荐
2401_cf3 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志3 小时前
idea整合maven环境配置
java·maven·intellij-idea
belldeep3 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP3 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
水银嘻嘻5 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
小嘟嚷ovo5 小时前
h5,原生html,echarts关系网实现
前端·html·echarts
十一吖i5 小时前
Vue3项目使用ElDrawer后select方法不生效
前端
只可远观5 小时前
Flutter目录结构介绍、入口、Widget、Center组件、Text组件、MaterialApp组件、Scaffold组件
前端·flutter
周胡杰5 小时前
组件导航 (HMRouter)+flutter项目搭建-混合开发+分栏效果
前端·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
无声旅者6 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi