Search code examples
ioc-containerspring.netxml-configuration

Optional Resources in Spring.Net


How to include Spring configuration files optionally? I think about something simular to this:

  <spring>
    <context>
      <resource uri="file:///Objects/RequiredObjects.xml" />
      <resource uri="file:///Objects/OptionalObjects.xml" required="false" />
    </context>

This way I could provide developers the possibility to override some configuration parts (e.g. for a local speed improvement or automatism during app startup) without affecting the app.config and the problem that a developer could checkin his modified file when it is not really his intent to change the config for all.


Solution

  • Not as simple as in AutoFac (because there is already a builtin way) but possible to achieve something similar with a little coding:

    using System.IO;
    using System.Xml;
    
    using Spring.Core.IO;
    
        public class OptionalFileSystemResource : FileSystemResource
        {
            public OptionalFileSystemResource(string uri)
                : base(uri)
            {
            }
    
            public override Stream InputStream
            {
                get
                {
                    if (System.IO.File.Exists(this.Uri.LocalPath))
                    {
                        return base.InputStream;
                    }
    
                    return CreateEmptyStream();
                }
            }
    
            private static Stream CreateEmptyStream()
            {
                var xml = new XmlDocument();
                xml.LoadXml("<objects />");
                var stream = new MemoryStream();
                xml.Save(stream);
                stream.Position = 0;
    
                return stream;
            }
        }
    

    Register a section handler:

    <sectionGroup name="spring">
         ...
          <section name="resourceHandlers" type="Spring.Context.Support.ResourceHandlersSectionHandler, Spring.Core"/>
         ...
    </sectionGroup>
    
    ...
    
    <spring>
      <resourceHandlers>
        <handler protocol="optionalfile" type="MyCoolStuff.OptionalFileSystemResource, MyCoolStuff" />
      </resourceHandlers>
    
      ...
    
    <context>
      <resource uri="file://Config/MyMandatoryFile.xml" />
      <resource uri="optionalfile://Config/MyOptionalFile.xml" />
      ...
    

    You'll find more information about resources and resource handlers in the Spring.Net documentation.