AppService returns ID 为空的 DTO

AppService returns DTO with null Id

我正在实施 AppService 和 DomainService。

域服务:

public class TagsManager : IDomainService
{
    private readonly IRepository<Tag, long> _tagRepository;
    private readonly IUnitOfWorkManager _unitOfWorkManager;

    public TagsManager(IRepository<Tag, long> tagRepository, IUnitOfWorkManager unitOfWorkManager)
    {
        _tagRepository = tagRepository;
        _unitOfWorkManager = unitOfWorkManager;
    }

    public IQueryable<Tag> Tags
    {
        get { return _tagRepository.GetAll(); }
    }
}

在 AppService 中使用 DomainService 时:

[UnitOfWork(IsDisabled = true)]
public async Task<TagDto> CreateTag(CreateTagInput input)
{
    var existing = await _tagsManager.Tags.Where(p => p.Type == input.Type && p.Value == input.Value.Trim()).FirstOrDefaultAsync();
    if (existing != null) throw new UserFriendlyException(L("ExistedRepeatedTag"));
    var newEntity = ObjectMapper.Map<Tag>(input);
    await _tagsManager.CreateTag(newEntity);
    return ObjectMapper.Map<TagDto>(newEntity);
}

会抛出异常:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

如果我注释掉[UnitOfWork(IsDisabled = true)],我将需要_unitOfWorkManager来保存记录。否则,在我的 Test 项目中,下面的代码 returns tag 为 null Id.

var tag = await _tagAppService.CreateTag(new CreateTagInput
{
    Value = createTag
});

不要禁用 UnitOfWork。映射前需要调用SaveChanges

// [UnitOfWork(IsDisabled = true)]
public async Task<TagDto> CreateTag(CreateTagInput input)
{
    var existing = await _tagsManager.Tags.Where(p => p.Type == input.Type && p.Value == input.Value.Trim()).FirstOrDefaultAsync();
    if (existing != null) throw new UserFriendlyException(L("ExistedRepeatedTag"));
    var newEntity = ObjectMapper.Map<Tag>(input);
    await _tagsManager.CreateTag(newEntity);

    // await _unitOfWorkManager.Current.SaveChangesAsync();
    await CurrentUnitOfWork.SaveChangesAsync();

    return ObjectMapper.Map<TagDto>(newEntity);
}