Embedding views as resources in NancyFx

Embedding views as resources in NancyFx.

I will assume you already have Nancy setup with views.

Step 1. Change the properties of your Views

For each of your views

  • Change "Build Action" to "Embedded Resource"
  • Change "Copy to Output Directory" to "Do Not Copy"

Step 2. Add a Bootstrapper or change your existing one

This tells Nancy to use the ResourceViewLocationProvider when searching for Views.

* Note: * you need change "NancyEmbeddedViews.MyViews" to be the resource prefix of your views. Generally, in Visual Studio, this will be "YourAssemblyName.PathToViewDirectory"

public class MyBootstrapper : DefaultNancyBootstrapper 
{
    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        base.ConfigureApplicationContainer(container);
        //This should be the assembly your views are embedded in
        var assembly = GetType().Assembly;
        ResourceViewLocationProvider
            .RootNamespaces
            //TODO: replace NancyEmbeddedViews.MyViews with your resource prefix
            .Add(assembly, "NancyEmbeddedViews.MyViews");
    }

    protected override NancyInternalConfiguration InternalConfiguration
    {
        get
        {
            return NancyInternalConfiguration.WithOverrides(OnConfigurationBuilder);
        }
    }

    void OnConfigurationBuilder(NancyInternalConfiguration x)
    {
        x.ViewLocationProvider = typeof (ResourceViewLocationProvider);
    }
}

Done

Your views should operate as previously but there is no need to deploy the view files.

Sample Code

There is a full working sample here:

http://simonsexperiments.googlecode.com/hg/NancyEmbeddedViews

Posted by: Simon Cropp
Last revised: 24 Dec, 2011 05:21 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.