Question

I've got my ASP.NET MVC 3 Web Application up and running with the Facebook C# SDK.

Following the instructions here, it seems as though once you put in the AppId / Secret in the web config section instructed, that is the settings pulled back when using FacebookApplication.Current, e.g:

var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current) 
{
   RedirectUri = new Uri(RedirectUrl)
};

My Web Application is "white labeled" so it serves two websites, with two seperate Facebook Applications.

Previously when i implemented Facebook Connect, i had a global property called "FacebookApplicationId", which looked at the domain and worked out which app id to use.

Is there a graceful way to do this with the Facebook C# SDK?

I could just do this:

var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current) 
{
     RedirectUri = new Uri(RedirectUrl),
     AppId = ManuallyGetTheRightAppIdBasedOnDomain(),
     AppSecret = ManuallyGetTheRightAppSecretBasedOnDomain()
};

But that seems un-DRY as i'll have to keep doing that.

Is there a way i can put some smarts in FacebookApplication.Current, so that the AppId and AppSecret properties are already set?

Open to any and all suggestions.

Was it helpful?

Solution

Think i got it: the ctor for FacebookOAuthClient takes a IFacebookApplication.

So i created a concrete implementation called WhiteLabeledFacebookApplication, which implements IFacebookApplication.

WhiteLabeledFacebookApplication's ctor takes a WebsiteType enum, so the properties for AppId and AppSecret read the relevant values from the web.config based on the enum passed through in the ctor.

So, in my FacebookController, (where i do all the FB stuff), i have a private property called CurrentFacebookApplication:

private IFacebookApplication _currentFacebookApplication;
private IFacebookApplication CurrentFacebookApplication
{
   get
   {
      if (_currentFacebookApplication == null)
      {
         var websiteType = SomeUnimportantCodeWhichWorksOutWebsiteFromUrl();
         _currentFacebookApplication = new WhiteLabeledFacebookApplication(websiteType );
      }

      return _currentFacebookApplication;
   }
}

So i can do this:

var oAuthClient = new FacebookOAuthClient(CurrentFacebookApplication) 
{
   RedirectUri = new Uri(RedirectUrl)
};

And the correct AppId/Secret will be pulled back - groovy!

The only thing i wish i could do is use dependency injection, but during construction of controllers, there is no HttpContext so i can't work out the website type.

Still, works well - fairly DRY.

Hats off to the developers for the toolkit for using interface-driven programming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top