1.使用xUnit測試項目建立一個測試工程,建一個DependencyInjection文件夾裏面添加DI_Test.cs文件redis
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注入的實現類,讀者能夠根據本身的代碼注入,本文僅供參考學,不提供具體實現代碼。json