예제 #1
0
        public void Store(AggregateRoot aggregate)
        {
            if (aggregate == null)
            {
                throw new ArgumentNullException(nameof(aggregate));
            }

            var eventStream = new EventStream();

            GenerateId(eventStream, aggregate);
            documentSession.Store(eventStream);
            aggregate.SetId(eventStream.Id);
            var eventStreamAndAggregateRoot = new EventStreamAndAggregateRoot(eventStream, aggregate);

            unitOfWork.Add(eventStreamAndAggregateRoot);
            entitiesByKey.Add(eventStream.Id, eventStreamAndAggregateRoot);
        }
예제 #2
0
        public TAggregate Load <TAggregate>(string id) where TAggregate : AggregateRoot
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (entitiesByKey.TryGetValue(id, out EventStreamAndAggregateRoot unitOfWorkInstance))
            {
                return((TAggregate)unitOfWorkInstance.AggregateRoot);
            }
            EventStream stream = documentSession.Load <EventStream>(id);

            if (stream != null)
            {
                TAggregate instance;

                // attempt to call default constructor
                // if none found, create uninitialized object
                ConstructorInfo ctor =
                    typeof(TAggregate).GetConstructor(
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                        null,
                        Type.EmptyTypes,
                        null);
                if (ctor != null)
                {
                    instance = (TAggregate)ctor.Invoke(null);
                }
                else
                {
                    instance = (TAggregate)FormatterServices.GetUninitializedObject(typeof(TAggregate));
                }

                instance.LoadFromHistory(stream.History);
                var eventStreamAndAggregateRoot = new EventStreamAndAggregateRoot(stream, instance);
                unitOfWork.Add(eventStreamAndAggregateRoot);
                entitiesByKey.Add(id, eventStreamAndAggregateRoot);
                return(instance);
            }

            return(null);
        }