0

One more follow up to Extract BearerToken from LinqToTwitter IAuthorizer

I am successfully using the Auth / Context / BearerToken with in my application however i wanted to now use the L2T library to Check on Rates. I need TwitterContext to do so, but I am now out of twitterCtx scope.

is it possible to set this up as a public class so I can access it from anywhere without the need to reauthorize?

Thank you in advance.

1 Answers1

1

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.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60