I've not seen change events being used in repository pattern implementations, but I'd like to have my repository like this:
interface IEntityRepository
{
event EventHandler<EntityChangedEventArgs> EntityAdded;
event EventHandler<EntityChangedEventArgs> EntityRemoved;
IEnumerable<Entity> GetAll();
Entity GetById(int id);
}
This is largely because my entities can be added and removed from the outside only, and not by the client of IEntityRepository.
Am I thinking fundamentally wrong about the repository pattern by doing like this, or do I have a valid case?
I'd say yes, if you intend to use Fowler's actual Repository Pattern. That pattern is intended to be a mediator between business and data layers by exposing a collection-like interface. It was not intended to actually hold data. That said, if you merely want to create a collection that wraps an API and exposes events when things change, by all means do so. Sometimes you don't need to follow a predefined pattern.
If you want it to be a pattern, I'd say it looks more like an Object Pool or Observer pattern. Consider the case of IObservable
using Reactive Extensions (Rx). It would allow you to react to the PInvoke layer, and force your responsibilities down the line. The code actually winds up being more effective than events. By using events, you have to maintain this repository, keep track of object lifetime, probably make this repository a singleton and give it some thread management. With Rx, you simply push an action on the observer's queue.
But in the end, use whatever feels most natural to you. Patterns are just suggestions, and don't always exist for every potential use case. This is one of those cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With