.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注入的实现类,读者可以根据自己的代码注入,本文仅供参考学,不提供具体实现代码。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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代理技术深度解析与实战指南