There are different ways to do this. Here are a couple where you can go the Singleton route or a factory method.
Note: There's debate on whether a Singleton is an appropriate pattern to use or whether a global reference to an object is even
appropriate at all, but that's isn't what you're asking.
public class TwitterContextService
{
static TwitterContext twitterCtx;
public static TwitterContext Instance
{
get
{
if (twitterCtx == null)
twitterCtx = CreateTwitterContext();
return twitterCtx;
}
}
public static TwitterContext CreateTwitterContext()
{
var auth = new ApplicationOnlyAuthorizer()
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerKey),
ConsumerSecret = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerSecret)
},
};
return new TwitterContext(auth);
}
}
Then there are two ways you can use this -
as a singleton:
TwitterContext twitterCtx = TwitterContextService.Instance;
or as a factory method:
TwitterContext twitterCtx = TwitterContextService.CreateTwitterContext();
Alternatively, you can use an IoC container (tons of information and available libraries on the Web) and pass the dependencies into the code that uses TwitterContext. I guess there are several different ways to do this.