public void SetUp()
            {
                _fixture = new CustomAutoFixture();

                _expectedContextManageCount = _hasCurrentContext ? 0 : 1;

                _contextService = _fixture.Freeze <IContextService <DbContext_Fake> >();
                _dbSetService   = _fixture.Freeze <IDbSetService <DbContext_Fake, Foo> >();
                _flushService   = _fixture.Freeze <IFlushService <DbContext_Fake> >();

                _context = new DbContext_Fake();

                _contextService.HasCurrentContext().Returns(_hasCurrentContext);
                _contextService.InitContext().Returns(_context);
                _contextService.GetCurrentContext().Returns(_context);

                _dbSet = Substitute.For <DbSet <Foo>, IQueryable <Foo> >();

                _dbSetService.GetDbSet(Arg.Any <DbContext_Fake>())
                .Returns(_dbSet);

                _sut = _fixture.Create <ContextRepository <DbContext_Fake, Foo> >();

                _foo = _fixture.Create <Foo>();
            }
            public void SetUp()
            {
                _fixture = new CustomAutoFixture();

                _expectedContextManageCount = _hasCurrentContext ? 0 : 1;

                _contextService = _fixture.Freeze <IContextService <DbContext_Fake> >();
                _dbSetService   = _fixture.Freeze <IDbSetService <DbContext_Fake, Foo> >();

                _context = new DbContext_Fake();

                _contextService.HasCurrentContext().Returns(_hasCurrentContext);
                _contextService.InitContext().Returns(_context);
                _contextService.GetCurrentContext().Returns(_context);

                _expectedEntity = _fixture.Create <Foo>();

                _dbSet = CreateDbSetSubstitute(_expectedEntity);
                _dbSet.FindAsync(_expectedEntity.FooId).Returns(_expectedEntity);

                _dbSetService.GetDbSet(Arg.Any <DbContext_Fake>())
                .Returns(_dbSet);

                _sut = _fixture.Create <ContextRepository <DbContext_Fake, Foo> >();
            }
        public async Task AddAsync(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            var(context, hasOwnContext) = GetCurrentContext();
            try
            {
                await _dbSetService.GetDbSet(context)
                .AddAsync(entity);

                await _flushService.FlushChangesAsync(context);
            }
            finally
            {
                ClearOwnContext(hasOwnContext);
            }
        }