.NetCore测试单元使用AutoFac依赖注入

1.使用xUnit测试项目创建一个测试工程,建一个DependencyInjection文件夹里面添加DI_Test.cs文件

public class DI_Test
    {
        public IContainer DICollections()
        {  //获取项目路径
            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
       //日志          
            ILoggerFactory loggerFactory = new LoggerFactory();
            IServiceCollection services = new ServiceCollection();

            //读取配置文件
            IConfiguration configuration = new ConfigurationBuilder().AddJsonFile($"{basePath}appsettings.json", false, true).Build();
            services.AddSingleton(configuration);
            //注入NLog日志
            services.AddLogging(builder=> 
            {
                builder.AddConfiguration(configuration.GetSection("Logging")).AddNLog("NLog.config").AddDebug().AddConsole();
            });
            //添加到实体
            GlobalContext.Configuration = configuration;
            //获取配置实体
            GlobalContext.AppSettings = configuration.GetSection("Appsettings").Get<AppSettings>();
			//添加异常过滤
            services.AddControllers(options =>
            {
                options.Filters.Add<ExceptionAttribute>();//全局异常过滤器
            }).AddControllersAsServices();
			
            //注入redis
            CacheStorageFactory.InitCacheStorage(new RedisCacheStorageProvider(GlobalContext.AppSettings.RedisServerString));
			//注入数据库
            services.AddTransient<IActiveTransactionProvider>(o => new ActiveTransactionProvider(GlobalContext.AppSettings.DbConnetion));



            //实例化 AutoFac  容器  使用反射获取所有实现接口的类注入DI容器
            var container = new ContainerBuilder();
            container.RegisterModule<Framework.IOC.AutoFacModule>();
            container.Populate(services);
            //使用已进行的组件登记创建新容器
            var ApplicationContainer = container.Build();
            return ApplicationContainer;
        }
    }`

2.添加一个Service测试文件,使用Autofac调用方法类

public class AddressServiceTest
    {
        private readonly IAddressService  addressService;    //商品分类接口

        public AddressServiceTest()
        {
            var conllections = new DI_Test().DICollections();
            addressService = conllections.Resolve<IAddressService>();
        }

        /// <summary>
        /// 获取地址列表
        /// </summary>
        [Fact(DisplayName = "获取地址列表")]
        public async void GetProductCategory()
        {
            var response = await addressService.PageList(new Models.RequestModels.AddressPageListRequest { UserId= 86,MerchantId=47 });
            Assert.NotNull(response);
        }
    }

注意: Framework.IOC.AutoFacModule 类为自定义的Autofac注入的实现类,读者可以根据自己的代码注入,本文仅供参考学,不提供具体实现代码。

posted @   听海漫步  阅读(1244)  评论(1编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示