Archive for the ‘ASP.NET’ Category

Accessing Spring.NET From Global.asax.cs

February 26, 2009

Yesterday, I was working on a web application in which I wanted to use the EntityTranslatorService and EntityTranslator classes as can be found in the Smart Client Software Factory, simply because I like the concept behind these mappers.  My application also needs to be testable.  I am using Spring.NET’s Inversion Of Control + Dependency Injection mechanism.

I wanted the EntityTranslatorService to be a singleton, so I would only have to register the EntityTranslators once.  I figured it should be possible to create a ConfigurationService class, with a RegisterTranslators method that would allow me to access the singleton instance of the EntityTranslatorService in order to register the different translators I would be using.  And what better place to do this than the Application_Start EventHandler in the Global.asax.cs file of my web application?  That way, the entity translators would only have to be set up once.  I added the following piece of code to the Application_Start EventHandler:

IConfigurationService configurationService =
     SpringContextRegistry.Context.Resolve<IConfigurationService>();
configurationService.RegisterEntityTranslators();

(SpringContextRegistry.Context.Resolve is just a helper method I created to be able to resolve objects based on the string representation of their type.) 

Wrong!

As soon as I tried to run my application, I was presented with the following error message:

“WebSupportModule not initialized. Did you forget to add <add name=”Spring” type=”Spring.Context.Support.WebSupportModule, Spring.Web”/> to your web.config’s <httpModules>-section?”

Whoops…  I should have realized that the application would not have been fully initialized by the time I made my Spring.NET call…  The Spring.NET WebSupportModule wasn’t available yet.

It didn’t take me long to find the solution to the problem, though.  I just needed to move my code and put it in the Init() method:

public override void Application_Init()
{
     base.Init();
     IConfigurationService configurationService =
          SpringContextRegistry.Context.Resolve<IConfigurationService>();
     configurationService.RegisterEntityTranslators();
}

If you found this post helpful, please click below to “Kick” it:

kick it on DotNetKicks.com