开发者

Is it a code smell that a repository has change events?

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 wro开发者_StackOverflow社区ng 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.


I have a similar issue where I need to publish events to an event store for CUD operations against a database (not concerned about Read operations). Rather than modify my repo I instead created a decorator and injected it (using SimpleInjector). That satisfies the Open/Closed principle and Single Responsibility, and actually it's provided a much cleaner way to handle that requirement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜