We're developing a .NET 3.5 Windows Forms app, using LINQ to SQL and MVP. We have a DataRepository class for retrieving data:
public class DbUserRepository : IUserRepository
{
private IList<UserName> _users;
public IList<UserName> GetUserNames()
{
if (_users == null)
{
// retrieve _users from DB
}
return _users;
}
In order to cache the list of users across all instances of the DBUserRepository, we were going to use the Enterprise Library's Caching Application Block.
But it occured to me, couldn't I just make _users a static member? For some reason that seems like an "old school" way, but it works. Are there any downsides to doing this? Is this considered bad design?
private static IList<UserName> _users;
Thanks
The biggest down-side to doing this is exactly due to what static
means; although you can have many DbUserRepository
objects, they will always only share one _users
variable. Cases where this causes problems:
If your app ever becomes multi-threaded, and you want each thread to have its own distinct user repository (whether or not this is a concern depends on what the repository means in the context of your system)
Unit testing the DbUserRepository
class becomes trickier, because if you run multiple unit tests on this class, they will carry state along with them from test to test, meaning that the test-run becomes order dependent... which is pretty undesirable
for simple caching I think static variable is fine, just need to be a bit careful about using locks to protect multiple threads accessing the _users variable. However, a better approach might be using ASP.NET Cache class. I know it is in the System.Web namespace but you can use it outside of ASP.NET application too.
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