【发布时间】:2020-01-17 07:39:05
【问题描述】:
我正在尝试学习 IoC 和 DI,并将其合并到我在 Asp.NET Core 上的分层 webapi 项目中,以便我可以使用 SQLite 内存数据库伪造数据库上下文并测试我的服务层的行为。
我有几个 unitOfWorks,每个都包含存储库。每个数据库一个工作单元。其中一个如下所示:
public class GcgcUnitOfWork : IDisposable
{
private readonly GcgcContext _context;
public AssetRepository assetRepository;
public GcgcUnitOfWork(GcgcContext context)
{
_context = context;
assetRepository = new AssetRepository(_context);
}
public int Complete()
{
try
{
return _context.SaveChanges();
}
catch (Exception ex)
{
return 0;
}
}
public void Dispose()
{
_context.Dispose();
}
}
在我的服务层上,我使用这些工作单元。一些服务类与两个不同的工作单元交互。如下所示:
public class GcgcService : IGcgcService
{
public GcgcAssetDataDTO GetGcgcAssetData()
{
using (var uow = new GcgcUnitOfWork())
using (var uowLandornet = new LandornetUnitOfWork())
{
var result = new GcgcAssetDataDTO();
/**do something.*/
return result;
}
}
}
但是现在,为了测试服务层的行为,我需要将带有 db 上下文的存储库注入到服务层的构造函数中。所以我需要更改为如下内容:
public class AssetService
{
GcgcUnitOfWork _uow;
LandornetUnitOfWork _uow2;
public AssetService(GcgcUnitOfWork uow, LandornetUnitOfWork uow2)
{
_uow = uow;
_uow2 = uow2;
}
public List<GcgcAsset> GetAssets()
{
return _uow.assetRepository.GetAssets();
}
/*also use and interact with other service classes that use these unit of works as well*/
}
所以在我的测试项目中,我可以使用内存数据库数据库上下文的工作单元来实例化服务类。但是 using 语句呢?我将如何处理?有人遇到过我面临的类似问题吗?您认为还有其他更好的方法来构建系统吗?
谢谢你,祝你有美好的一天
【问题讨论】:
-
在您的 Complete 方法中,您返回 1 表示成功,返回 0 表示失败。不要那样做!您正在丢失有价值的异常信息!让异常冒泡到代码可以对其进行处理的程度。并删除你的 catch 块中无用的 if 块。
-
GetGcgcAssetData方法使用无参数构造函数创建GcgcUnitOfWork,但所示的GcgcUnitOfWork类只有一个带参数的构造函数。这使得很难理解问题是什么。代码到底是什么样子的?
标签: asp.net asp.net-core dependency-injection inversion-of-control repository-pattern