Skip to content

Instantly share code, notes, and snippets.

@yreynhout
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yreynhout/74b3bd2c844e1c7dfd12 to your computer and use it in GitHub Desktop.
Save yreynhout/74b3bd2c844e1c7dfd12 to your computer and use it in GitHub Desktop.
Goodbye repository, Hello aggregate reader!
public class AggregateReader
{
private readonly Func<IAggregateRootEntity> _rootFactory;
private readonly IEventStoreConnection _connection;
private readonly EventStoreReaderConfiguration _configuration;
public AggregateReader(
Func<IAggregateRootEntity> rootFactory,
IEventStoreConnection connection,
EventStoreReaderConfiguration configuration)
{
if (rootFactory == null) throw new ArgumentNullException("rootFactory");
if (connection == null) throw new ArgumentNullException("connection");
if (configuration == null) throw new ArgumentNullException("configuration");
_rootFactory = rootFactory;
_connection = connection;
_configuration = configuration;
}
public async Task<ReadResult<Aggregate>> ReadAsync(string identifier)
{
if (identifier == null) throw new ArgumentNullException("identifier");
var stream = _configuration.StreamNameResolver.Resolve(identifier);
var streamCredentials = _configuration.StreamUserCredentialsResolver.Resolve(stream);
var slice = await _connection.
ReadStreamEventsForwardAsync(stream, StreamPosition.Start, _configuration.SliceSize, false, streamCredentials);
if (slice.Status == SliceReadStatus.StreamNotFound)
return ReadResult<Aggregate>.NotFound;
if (slice.Status == SliceReadStatus.StreamDeleted)
return ReadResult<Aggregate>.Deleted;
var root = _rootFactory();
root.Initialize(slice.Events.Select(@event => _configuration.Deserializer.Deserialize(@event)));
while (!slice.IsEndOfStream)
{
slice = await _connection.
ReadStreamEventsForwardAsync(stream, slice.NextEventNumber, _configuration.SliceSize, false, streamCredentials);
if (slice.Status == SliceReadStatus.StreamNotFound)
return ReadResult<Aggregate>.NotFound;
if (slice.Status == SliceReadStatus.StreamDeleted)
return ReadResult<Aggregate>.Deleted;
root.Initialize(slice.Events.Select(@event => _configuration.Deserializer.Deserialize(@event)));
}
return new ReadResult<Aggregate>(new Aggregate(identifier, slice.LastEventNumber, root));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment