Tuesday Sep 22, 2009

Sample: Generic GetObject extension method for Spring.NET

I know there's some controversy about whether or not this is a good thing - the stock interface is more flexible in that it won't go undefined if the context has multiple instances of a type. I guess I just think it's odd that you'd have by-type autowiring and not something like this... Here's a sample implementation of an extension method implementing a GetObject<T>() method on a Spring.NET application context that could go anywhere:

static class Program
{
/// /// The main entry point for the application. /// [STAThread] static void Main() { //Get the default configured context from the .NET application configuration. using (IApplicationContext appContext = ContextRegistry.GetContext()) {
CustomerEntryForm customerEntryForm = appContext.GetObject<CustomerEntryForm>();
                Application.Run(customerEntryForm);
}
}
public static T GetObject<T>(this IApplicationContext appCtx)
        {
IDictionary obectsOfType = appCtx.GetObjectsOfType(typeof(T));

if (obectsOfType.Count != 1)
throw new ApplicationException("Expected exactly one instance of type " + typeof(T).FullName +
" in Spring.NET context, but found " + obectsOfType.Count);

T retVal = default(T);

foreach (object key in obectsOfType.Keys)
retVal = (T) obectsOfType[key];

return retVal;
}
}

Comments:

Hi,

The solution looks nice.

I see you are making a casting operation inside the foreach loop

retVal = (T) obectsOfType[key];

We may have a better performance if we avoid the casting operation.

I made an update in the code to remove it. So, it looks like this:

public static T GetObject<T>(this IApplicationContext appCtx)
{
ICollection objectsOfType = appCtx.GetObjectsOfType(typeof(T)).Values;
if (objectsOfType.Count != 1)
{
throw new ApplicationException("Expected exactly one instance of type " + typeof(T).FullName + " in Spring.NET context, but found " + objectsOfType.Count);
}

T retVal = default(T);
foreach (T key in objectsOfType)
{
retVal = key;
}

return retVal;
}

We remove one instruction in the code, the cast operation, so the code is a bit more faster

Posted by Daniel Hernandez on November 22, 2009 at 02:13 PM PST #

Post a Comment:
  • HTML Syntax: Allowed