Saturday, January 26, 2013

4 easy steps to auto-merge configuration settings as part of package installation

Usually, installing a package through NuGet corresponds to a set of assemblies whose references get added to the consuming system. However, some packages contain more than mere assembly references. They may also expose certain configuration settings that are required for the assemblies to work. Creating .nupkg packages (either using project reference or .nuspec file) for such applications isn't straightforward. We should let NuGet know that it has to pack certain additional content when it creates the .nupkg file.
 
So, here are 4 easy steps to auto-import configuration settings as part of package installation -
  1. Add a folder names 'content' and place it in the same folder as where the .nuspec file resides.
  2. Add an empty .config file to the content folder
    • If all the consumers are web-based, then, name it web.config.transform.
    • If all the consumers are non-web (Ex: Console Apps, Desktop apps, etc..), then, name it app.config.transform.
    • If consumers are a mix of both the above, then, name it web.config.transform and add a new file named app.config.transform --- in this case, NuGet will decide which one to pick at the time of installation, based on the consuming application.
  3. Pick the configuration settings required from the project configuration file and copy such values to the new file(s) created.
  4. Now, carefully, pick all the parent tags of those values copied above from the project configuration file and add as parents in the new file(s) created(in step #2) --- make sure you add closing tags corresponding to whatever node is newly added.

Once these 4 steps are done, then use the .nuspec file to create the package. Now, when consumers try to install such package, then, their configuration files would get auto-merged (Not replaced) with the settings present in the .config.transform files we created in step #2.

While this looks to be a cool feature, it is actually a much wider feature of NuGet, where you can even add transforms to source code, add PowerShell scripts to be auto-run, etc.. Refer this section on the official NuGet documentation on this for its full power.

PS: Please comment if this served your purpose by any chance. Happy coding :)

No comments:

Post a Comment

Please help to make the post more helpful with your comments.