![]() |
This chapter includes a grab bag of quickstart examples for using the Spring.NET framework. The source material for this simple demonstration of Spring.NET's IoC features is lifted straight from Martin Fowler's article that discussed the ideas underpinning the IoC pattern. See Inversion of Control Containers and the Dependency Injection pattern for more information. The motivation for basing this quickstart example on said article is because the article is pretty widely known, and most people who are looking at IoC for the first time typically will have read the article (at the time of writing a simple Google search for 'IoC' yields the article in the first five results). Fowler's article used the example of a search facility for movies to
illustrate IoC and Dependency Injection (DI). The article described how a
The The C# code listings for the MovieFinder application can be found in
the ![]() The startup class for the MovieFinder example is the
using System; namespace Spring.Examples.MovieFinder { public class MovieApp { public static void Main () { } } } What we want to do is get a reference to an instance of the
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> </configSections> <spring> <context> <resource uri="config://spring/objects"/> </context> <objects xmlns="http://www.springframework.net"> <description>An example that demonstrates simple IoC features.</description> </objects> </spring> </configuration> The objects that will be used in the example application will be
configured as XML The body of the using System; using Spring.Context; ... public static void Main () { IApplicationContext ctx = ContextRegistry.GetContext(); } ... As can be seen in the above C# snippet, a
IApplicationContext ctx = ContextRegistry.GetContext();
... retrieves a fully configured As yet, no objects have been defined in the application config
file, so let's do that now. The very miminal XML definition for the
<objects xmlns="http://www.springframework.net"> <object name="MyMovieLister" type="Spring.Examples.MovieFinder.MovieLister, Spring.Examples.MovieFinder"> </object> </objects> Notice that the full, assembly-qualified name of the
... public static void Main () { IApplicationContext ctx = ContextRegistry.GetContext(); MovieLister lister = (MovieLister) ctx.GetObject ("MyMovieLister"); } ... The <objects xmlns="http://www.springframework.net"> <object name="MyMovieFinder" type="Spring.Examples.MovieFinder.SimpleMovieFinder, Spring.Examples.MovieFinder"/> </object> </objects> What we want to do is inject the <objects xmlns="http://www.springframework.net"> <object name="MyMovieLister" type="Spring.Examples.MovieFinder.MovieLister, Spring.Examples.MovieFinder"> <!-- using setter injection... --> <property name="movieFinder" ref="MyMovieFinder"/> </object> <object name="MyMovieFinder" type="Spring.Examples.MovieFinder.SimpleMovieFinder, Spring.Examples.MovieFinder"/> </object> </objects> When the ... public static void Main () { IApplicationContext ctx = ContextRegistry.GetContext(); MovieLister lister = (MovieLister) ctx.GetObject ("MyMovieLister"); Movie[] movies = lister.MoviesDirectedBy("Roberto Benigni"); Console.WriteLine ("\nSearching for movie...\n"); foreach (Movie movie in movies) { Console.WriteLine ( string.Format ("Movie Title = '{0}', Director = '{1}'.", movie.Title, movie.Director)); } Console.WriteLine ("\nMovieApp Done.\n\n"); } ... To help ensure that the XML configuration of the MovieLister class must specify a value for the MovieFinder property, you can add the [Required] attribute to the MovieLister's MovieFinder property. The example code shows uses this attribute. For more information on using and configuring the [Required] attribute, refer to this section of the reference documentation. Let's define another implementation of the
... <object name="AnotherMovieFinder" type="Spring.Examples.MovieFinder.ColonDelimitedMovieFinder, Spring.Examples.MovieFinder"> </object> ... This XML snippet describes an
IMovieFinder finder = (IMovieFinder) ctx.GetObject ("AnotherMovieFinder");
will result in a fatal
... <object name="AnotherMovieFinder" type="Spring.Examples.MovieFinder.ColonDelimitedMovieFinder, Spring.Examples.MovieFinder"> <constructor-arg index="0" value="movies.txt"/> </object> ... Unsurprisingly, the <constructor-arg/> element is used to
supply constructor arguments to the constructors of managed objects. The
Spring.NET IoC container uses the functionality offered by
So now we have two implementations of the
... <object name="MyMovieLister" type="Spring.Examples.MovieFinder.MovieLister, Spring.Examples.MovieFinder"> <!-- lets use the colon delimited implementation instead --> <property name="movieFinder" ref="AnotherMovieFinder"/> </object> <object name="MyMovieFinder" type="Spring.Examples.MovieFinder.SimpleMovieFinder, Spring.Examples.MovieFinder"/> </object> <object name="AnotherMovieFinder" type="Spring.Examples.MovieFinder.ColonDelimitedMovieFinder, Spring.Examples.MovieFinder"> <constructor-arg index="0" value="movies.txt"/> </object> ... Note that there is no need to recompile the application to effect
this change of implementation... simply changing the application config
file and then restarting the application will result in the Spring.NET
IoC container injecting the colon delimited implementation of the
This example application is quite simple, and admittedly it doesn't do a whole lot. It does however demonstrate the basics of wiring together an object graph using an intuitive XML format. These simple features will get you through pretty much 80% of your object wiring needs. The remaining 20% of the available configuration options are there to cover corner cases such as factory methods, lazy initialization, and suchlike (all of the configuration options are described in detail in the Chapter 5, The IoC container). Often enough the first use of Spring.NET is also a first introduction to log4net. To kick start your understanding of log4net this section gives a quick overview. The authoritative place for information on log4net is the log4net website. Other good online tutorials are Using log4net (OnDotNet article) and Quick and Dirty Guide to Configuring Log4Net For Web Applications. Spring.NET is using version 1.2.9 whereas most of the documentation out there is for version 1.2.0. There have been some changes between the two so always double check at the log4net web site for definitive information. Also note that we are investigating using a "commons" logging library so that Spring.NET will not be explicity tied to log4net but will be able to use other logging packages such as NLog and Microsoft enterprise logging application block. The general usage pattern for log4net is to configure your loggers, (either in App/Web.config or a seperate file), initialize log4net in your main application, declare some loggers in code, and then log log log. (Sing along...) We are using App.config to configure the loggers. As such, we declare the log4net configuration section handler as shown below <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> The corresponding configuration section looks like this <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <!-- Set default logging level to DEBUG --> <root> <level value="DEBUG" /> <appender-ref ref="ConsoleAppender" /> </root> <!-- Set logging for Spring to INFO. Logger names in Spring correspond to the namespace --> <logger name="Spring"> <level value="INFO" /> </logger> </log4net> The appender is the output sink - in this case the console. There are a large variety of output sinks such as files, databases, etc. Refer to the log4net Config Examples for more information. Of interest as well is the PatternLayout which defines exactly the information and format of what gets logged. Usually this is the date, thread, logging level, logger name, and then finally the log message. Refer to PatternLayout Documentation for information on how to customize. The logging name is up to you to decide when you declare the logger in code. In the case of this example we used the convention of giving the logging name the name of the fully qualified class name. private static readonly ILog LOG = LogManager.GetLogger(typeof (MovieApp)); Other conventions are to give the same logger name across multiple classes that constitute a logical component or subsystem within the application, for example a data access layer. One tip in selecting the pattern layout is to shorten the logging name to only the last 2 parts of the fully qualified name to avoid the message sneaking off to the right too much (where can't see it) because of all the other information logged that precedes it. Shortening the logging name is done using the format %logger{2}. To initialize the logging system add the following to the start of your application XmlConfigurator.Configure(); Note that if you are using or reading information on version 1.2.0 this used to be called DOMConfigurator.Configure(); The logger sections associate logger names with logging levels and appenders. You have great flexibility to mix and match names, levels, and appenders. In this case we have defined the root logger (using the special tag root) to be at the debug level and have an console sink. We can then specialize other loggers with different setting. In this case, loggers that start with "Spring" in their name are logged at the info level and also sent to the console. Setting the value of this logger from INFO to DEBUG will show you detailed logging information as the Spring container goes about its job of creating and configuring your objects. Coincidentally, the example code itself uses Spring in the logger name, so this logger also controls the output level you see from running MainApp. Finally, you are ready to use the simple logger api to log, i.e. LOG.Info("Searching for movie..."); Logging exceptions is another common task, which can be done using the error level try { //do work { catch (Exception e) { LOG.Error("Movie Finder is broken.", e); } The example program The application context configuration file contains an object
definition with the name The ... <object name="messageSource" type="Spring.Context.Support.ResourceSetMessageSource, Spring.Core"> <property name="resourceManagers"> <list> <value>Spring.Examples.AppContext.Images, Spring.Examples.AppContext</value> <ref object="myResourceManager"/> </list> </property> </object> <object name="myResourceManager" type="Spring.Objects.Factory.Config.ResourceManagerFactoryObject, Spring.Core"> <property name="baseName"> <value>Spring.Examples.AppContext.MyResource</value> </property> <property name="assemblyName"> <value>Spring.Examples.AppContext</value> </property> </object> ... The main application creates the application context and then
retrieves various resources via their key names. In the code all the key
names are declared as static fields in the class
string msg = ctx.GetMessage(Keys.HELLO_MESSAGE, CultureInfo.CurrentCulture, "Mr.", "Anderson"); retrieves the text string and replaces the placeholders in the string with the passed argument values resulting in the text, "Hello Mr. Anderson". The current culture is used to select the resource file MyResource.resx. If instead the Spanish culture is specified CultureInfo spanishCultureInfo = new CultureInfo("es"); string esMsg = ctx.GetMessage(Keys.HELLO_MESSAGE, spanishCultureInfo, "Mr.", "Anderson"); Then the resource file MyResource.es.resx is used instead as
in standard .NET localization. Spring is simply delegating to .NET
ResourceManager to select the appropriate localized resource. The
Spanish version of the resource differs from the English one in that the
text under the key As you can see in this example, the title "Mr." should not be used
in the case of the spanish localization. The title can be abstracted out
into a key of its own, called string[] codes = {Keys.FEMALE_GREETING}; DefaultMessageResolvable dmr = new DefaultMessageResolvable(codes, null); msg = ctx.GetMessage(Keys.HELLO_MESSAGE, CultureInfo.CurrentCulture, dmr, "Anderson"); will assign msg the value, Hello Mrs. Anderson, since the
value for the key
esMsg = ctx.GetMessage(Keys.HELLO_MESSAGE,
spanishCultureInfo,
dmr, "Anderson");
will assign esMsg the value, Hola Senora Anderson, since the
value for the key Localization can also apply to objects and not just strings. The .NET 1.1 framework provides the utility class ComponentResourceManager that can apply multiple resource values to object properties in a performant manner. (VS.NET 2005 makes heavy use of this class in the code it generates for winform applications.) The example program has a simple class, Person, that has an integer property Age and a string property Name. The resource file, Person.resx contains key names that follow the pattern, person.<PropertyName>. In this case it contains person.Name and person.Age. The code to assign these resource values to an object is shown below Person p = new Person(); ctx.ApplyResources(p, "person", CultureInfo.CurrentUICulture); While you could also use the Spring itself to set the properties of these objects, the configuration of simple properties using Spring will not take into account localization. It may be convenient to combine approaches and use Spring to configure the Person's object references while using IApplicationContext inside an AfterPropertiesSet callback (see IInitializingObject) to set the Person's culture aware properties. The example program
Loosely coupled eventing is normally associated with Message
Oriented Middleware (MOM) where a daemon process acts as a message
broker between other independent processes. Processes communicate
indirectly with each other by sending messages though the message
broker. The process that initiates the communication is known as a
publisher and the process that receives the message is known as the
subscriber. By using an API specific to the middleware these processes
register themselves as either publishers or subscribers with the message
broker. The communication between the publisher and subscriber is
considered loosely coupled because neither the publisher nor subscriber
has a direct reference to each other, the messages broker acts as an
intermediary between the two processes. The
The In this example the class The publisher and subscriber classes are defined in an application
context configuration file but that is not required in order to
participate with the event registry. The main program,
The publisher then fires the event using normal .NET eventing semantics and the subscriber is called. The subscriber prints a message to the console and sets a state variable to indicate it has been called. The program then simply prints the state variable of the two subscribers, showing that only one of them (the one that registered with the event registry) was called.
The idea is to build an executor backed by a pool of
Some information on
A Last but not least, this executor can be shut down in a few different ways (please refer to the Spring.NET SDK documentation). Given its simplicity, it is very powerful.
The example project
This executor will be used to implement a parallel
recursive
In order to use the
In our case, as already said, we want to to implement a pool
of public class QueuedExecutorPoolableFactory : IPoolableObjectFactory { the first task a factory should do is to create objects: object IPoolableObjectFactory.MakeObject() { // to actually make this work as a pooled executor // use a bounded queue of capacity 1. // If we don't do this one of the queued executors // will accept all the queued IRunnables as, by default // its queue is unbounded, and the PooledExecutor // will happen to always run only one thread ... return new QueuedExecutor(new BoundedBuffer(1)); } and should be also able to destroy them: void IPoolableObjectFactory.DestroyObject(object o) { // ah, self documenting code: // Here you can see that we decided to let the // executor process all the currently queued tasks. QueuedExecutor executor = o as QueuedExecutor; executor.ShutdownAfterProcessingCurrentlyQueuedTasks(); }
When an object is taken from the pool, to satisfy a client request, may be the object should be activated. We can possibly implement the activation like this: void IPoolableObjectFactory.ActivateObject(object o) { QueuedExecutor executor = o as QueuedExecutor; executor.Restart(); }
even if a After activation, and before the pooled object can be succesfully returned to the client, it is validated (should the object be invalid, it will be discarded: this can lead to an empty unusable pool [5]). Here we check that the worker thread exists: bool IPoolableObjectFactory.ValidateObject(object o) { QueuedExecutor executor = o as QueuedExecutor; return executor.Thread != null; }
Passivation, symmetrical to activation, is the process a pooled object is subject to when the object is returned to the pool. In our case we simply do nothing: void IPoolableObjectFactory.PassivateObject(object o) { }
At this point, creating a pool is simply a matter of creating an
pool = new SimplePool(new QueuedExecutorPoolableFactory(), size);
Taking advantage of the using (PooledObjectHolder holder = PooledObjectHolder.UseFrom(pool))
{
QueuedExecutor executor = (QueuedExecutor) holder.Pooled;
executor.Execute(runnable);
} without worrying about obtaining and returning an object from/to the pool. Here is the implementation: public class PooledObjectHolder : IDisposable { IObjectPool pool; object pooled; /// <summary> /// Builds a new <see cref="PooledObjectHolder"/> /// trying to borrow an object form it /// </summary> /// <param name="pool"></param> private PooledObjectHolder(IObjectPool pool) { this.pool = pool; this.pooled = pool.BorrowObject(); } /// <summary> /// Allow to access the borrowed pooled object /// </summary> public object Pooled { get { return pooled; } } /// <summary> /// Returns the borrowed object to the pool /// </summary> public void Dispose() { pool.ReturnObject(pooled); } /// <summary> /// Creates a new <see cref="PooledObjectHolder"/> for the /// given pool. /// </summary> public static PooledObjectHolder UseFrom(IObjectPool pool) { return new PooledObjectHolder(pool); } }
Please don't forget to destroy all the pooled istances once you have
finished! How? Well using something like this in
public void Stop () { // waits for all the grep-task to have been queued ... foreach (ISync sync in syncs) { sync.Acquire(); } pool.Close(); }
The use of the just built executor is quite straigtforward but a little tricky if we want to really exploit the pool. private PooledQueuedExecutor executor; public ParallelGrep(int size) { executor = new PooledQueuedExecutor(size); } public void Recurse(string startPath, string filePattern, string regexPattern) { foreach (string file in Directory.GetFiles(startPath, filePattern)) { executor.Execute(new Grep(file, regexPattern)); } foreach (string directory in Directory.GetDirectories(startPath)) { Recurse(directory, filePattern, regexPattern); } } public void Stop() { executor.Stop(); }
public static void Main(string[] args) { if (args.Length < 3) { Console.Out.WriteLine("usage: {0} regex directory file-pattern [pool-size]", Assembly.GetEntryAssembly().CodeBase); Environment.Exit(1); } string regexPattern = args[0]; string startPath = args[1]; string filePattern = args[2]; int size = 10; try { size = Int32.Parse(args[3]); } catch { } Console.Out.WriteLine ("pool size {0}", size); ParallelGrep grep = new ParallelGrep(size); grep.Recurse(startPath, filePattern, regexPattern); grep.Stop(); }
Refer to Chapter 38, AOP QuickStart. [5] You may think that we can provide a smarter implementation and you are probably right. However, it is not so difficult to create a new pool in case the old one became unusable. It could not be your preferred choice but surely it leverages simplicity and object immutability
|