.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注入的實現類,讀者可以根據自己的代碼注入,本文僅供參考學,不提供具體實現代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM