I have the following class:
public class SqlCeEventStore: EventStore
{
private EventStoreDB db;
public SqlCeEventStore(EventStoreDB db)
{
this.db = db;
}
public void Dispose()
{
db.Dispose();
}
}
My problem is this: am I correct in disposing the EventStoreDB in the Dispose method of my class, given that it was passed to it in the constructor (and thus, might conceivably be reused after my class is disposed)?
That is, if I dispose it I mandate that the correct usage of my class is:
using (var store = new SqlCeEventStore(new EventStoreDB)){
{
//...
}
but I can see this alternative call being used:
using (var db = new EventStoreDB())
using (var store = new SqlCeEventStore(db))
{
//...
}
in which case I should not dispose of the EventStoreDB from the SqlCeEventStore class.
Are there any arguments for one style or the other? I want to pick one and stick to it, and I’d rather not flip a coin 🙂
In general there is no rule to this, but yes I would agree that since the object was created outside your scope and was passed to you, you don’t own it.
If you had created it, then you should have all rights to do whatever you like to (with documenting the expected behavior for the callers)
This is the classical composition vs aggregation stuff.