Hi
When creating a repository class, eg. CustomerRepository, should my methods be static?
Or should I first instanciate the CustomerRepository class, and then call the public methods on the instance?
Which approach is best and why?
Thanks
Hi
When creating a repository class, eg. CustomerRepository, should my methods be static?
Or should I first instanciate the CustomerRepository class, and then call the public methods on the instance?
Which approach is best and why?
Thanks
I'd go with an instance
simply for unit testing - mocking for example is hard with a static
method.
Static
methods are death to testability.
Statics are hard to test, but at the same time, statics are eaier to call, everything can be brought down to one method instead of initiating repository and calling its method and closing repository. There are various ways to implement it, we have found following way is the best, because you can not override static methods so in future if you want to inherit and extend functionality, its little bit difficult.
Another approach we have is, we have instance method but we have one static variable.. for example...
CustomerRepository.Repository.GetAll();
and this is how its implemented...
class CustomerRepository{
// Only one static variable
public static CustomerRepository Repository = new CustomerRepository();
// all methods are instance methods..
public IEnumerable GetAll(){
...
}
}
I always create an interface which describes the contract for my repository.
Thus, I do not go down the route of static members.
Not only for testability which has already been mentionned, but also because of the fact that my repository needs to have a 'context'.
More specifically, I use NHibernate as an OR/M mapper, and I pass the ISession that should be used to the repository instance. By doing so, multiple repositories can use the same ISession (UnitOfWork), and thus, multiple different types can be persisted within the same transaction.
You should propably create an interface ICustomerRepository, and then create a class CustomerRepository that derives from from that interface.
The reason why is testability.
In tests you can now mock out the concrete instance of CustomerRepositotory with some mock object.
You can also easily replace implementations of this repository, add logging or caching.
As for statics. If you want to use static instance, it's better to use some Dependency Injection tool and set component's lifestyle to singleton. It still would be testable.