SpringNet
.NET, Blog, Software Development

Mutliple object definition files with Spring.Net

Spring.Net is a great IoC (Inversion of Control) framework that allows developers to implement Dependency Injection using an xml configuration. In most cases, the Spring config will end up in either your app/ web.config files. However, in some cases, it may be desirable or necessary to keep the Spring object definitions outside your app/web.config files in order to be able to share them across multiple projects, eg your website and your unit tests. The Spring.Net framework has a feature to allows us to do this easily, but there are a few caveats that I will mention below.

First you need to create and add a new xml file to your solution. For the sake of this tutorial we will name the file objects.obj and place it at the root of the solution. Open the xml and create the objects you need. Ensure that the xml has the following structure:

Any number of objects can be added to this file. Save and close.
The next step is to edit the web/app.config to reference the newly created file. There are two ways to import the file:
1. As a resource
2. As an import

If you want to add your object as a resource, you need to use the following syntax:

If you want to do an import, you need to use the following syntax:

The caveats, as I mentioned earlier are:
• The separate objects.xml file needs to be at the same level or any level below the app/web.config

• You can reference resource files that sit above the current level using the fully qualified resource path string like:

Note that file: protocol identifier is followed by four slashes, two belong to the protocol and two to the server location. Worked on my machine :)

• Alternatively, you can write your own or write you own IResourceHandler extends the base functionality according to your needs. More details about this can be found here

• The Spring.Net comes with in two flavors so in the web.config, make sure you reference the correct Spring library, Spring.Web as this allows referencing external resources using the following syntax:

And then call your resource like this:

Internally, the IResourceLoader will use the Server.Map.Path to locate the file you are attempting to import

Happy coding…

Standard