Loading solution user options with AsyncPackage (Visual Studio extension)

User-specific options at the solution level are stored in the .suo file. Back when it was the norm to have your extension inherits from the Package class, and therefore loaded synchronously by Visual Studio, you can have these options loaded by overriding the OnLoadOptions method. This method is automatically called by the platform for each option key that you previously specified (via Package.AddOptionKey). The OnLoadOptions method would look something like the below.

protected override void OnLoadOptions(string key, Stream stream)
{
	if (key.Equals("MyOption", StringComparison.InvariantCultureIgnoreCase))
	{
		_myOption = new StreamReader(stream).ReadToEnd();
	}
	else
	{
		base.OnLoadOptions(key, stream);
	}
}

Since synchronous loading of packages has been deprecated, your extension now should inherit from AsyncPackage (and have AllowsBackgroundLoading enabled and PackageAutoLoadFlags set to BackgroundLoad if applicable). When your package is loaded asynchronously in the background however, it may not have been loaded when the platform processes the .suo file, and therefore OnLoadOptions may not be called on your package, which results in user-specific options not being restored for the user.

A solution for this is to initiate the loading of solution user options in your own code (rather than relying on the platform). You can use the IVsSolutionPersistence.LoadPackageUserOpts method and pass in the option key to do this. Here are the steps:

  1. Make your package class implements IVsPersistSolutionOpts.
public sealed class MyExtensionPackage : AsyncPackage, IVsPersistSolutionOpts
  1. Add the following code to the package’s InitializeAsync method:
var solutionPersistenceService = GetService(typeof(IVsSolutionPersistence)) as IVsSolutionPersistence;

solutionPersistenceService.LoadPackageUserOpts(this, "MyOption");
solutionPersistenceService.LoadPackageUserOpts(this, "MyOption2");
//Other option keys

That’s it. Your OnLoadOptions method does not need to change.

Note that this will change the UX of your package slightly. When the user opens a solution in Visual Studio, they would be able to start using Visual Studio and work with the solution before your package finishes loading. This means that for a few seconds, the user options may not have been loaded, and this may confuse some users.

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in Visual Studio Extension. Bookmark the permalink.

1 Response to Loading solution user options with AsyncPackage (Visual Studio extension)

  1. Liang says:

    I cannot hit the OnLoadOptions() after following what you did.

Leave a comment