One option would have been to create an instance in the app's constructor. The downside to that approach is that I'd have to pass it into every method that might need it. Instead I chose to use the singleton pattern.
Below is a quick example. Marking the MyConfig class as static means it can't be instantiated. The static constructor will be called once and only once - the first time the class is accessed. This constructor creates an instance of the CommonConfig class, which can be accessed through the Config property. Now, regardless of how many times my code accesses MyConfig.Config, the database is only hit once.
public static class MyConfig
{
static readonly CommonConfig _commonConfig;
static MyConfig()
{
_commonConfig = new CommonConfig();
}
public static CommonConfig Config
{
get
{
return _commonConfig;
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.