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.uj5u.com/net/228245.html
標籤:.NET技术
