4
Spark bindings are a powerful tool to use when composing views. This article will show you how you can creating a custom binding provider to change the file location of your bindings file

Spark Bindings are a powerful tool provided by the Spark View Engine which allows you to override standard html tags or create new ones with custom behaviours.

On a project I was recently working on, we wanted to share a common bindings file across multiple projects, so we wanted to redefine where the bindings file was located. The modular nature of Spark makes this really easy.

The first thing you need to do is define a new IBindingProvider implementation, or extend an existing one. If you wanted to completely redefine the way the bindings were setup, you could implement the IBindingProvider, however for what we needed to do, we could just extend the existing BindingProvider and change the bits that we needed.

The implementation below simply copies the existing DefaultBindingProvider provided in the spark source and changes the view location but it is pretty simple to put whatever logic you want in there.

public class CustomBindingProvider : BindingProvider
{
    public override IEnumerable<Binding> GetBindings(BindingRequest bindingRequest)
    {
        //Check if the location exists - could be any location
        if (bindingRequest.ViewFolder.HasView("~/SomeNewBindingsLocation/bindings.xml") == false)
            return new Binding[0];

        var bindings = new List<Binding>();

        var file = bindingRequest.ViewFolder.GetViewSource("~/SomeNewBindingsLocation/bindings.xml");
        using (var stream = file.OpenViewStream())
        {
            using (var reader = new StreamReader(stream))
            {
                bindings.AddRange(LoadStandardMarkup(reader));
            }
        }

        return bindings;
    }
}

Once you have your IBindingProvider you need to register it with Spark.

// Register Spark
var services = SparkEngineStarter.CreateContainer();

services.SetService<IBindingProvider>(new CustomBindingProvider());

SparkEngineStarter.RegisterViewEngine(services);   

And that's all there is to it.