.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注入的实现类,读者可以根据自己的代码注入,本文仅供参考学,不提供具体实现代码。

原文地址:https://www.cnblogs.com/nnnnnn/p/14061519.html