Wednesday, November 3, 2010

spring.net dynamic configuration. Configure IApplicationContext from GenericApplicationContext and file stream.

Use Case

Configure ApplicationContext from stream. This can be helpful when you don't know exact object configuration on designtime and have to create application context on runtime.

Solution

Spring.net gives us ability to manually configure configuration sources.

IApplicationContext ctx = null;
using (var sr = File.OpenRead("some config file")) {
               ctx = new GenericApplicationContext();
               var objectDefinitionReader = new XmlObjectDefinitionReader(ctx);
               objectDefinitionReader.LoadObjectDefinitions(new InputStreamResource(sr, "MsmqSendServiceGatewayConfiguration"));

               ctx.Refresh();
}

var svc = ctx["myService"] as IMyService;

The most important line in the code above is: ctx.Refresh(); By doing this, ApplicationContext is propagates to all objects supporting IApplicationContextAware interface. Without this line, invoking any object from context may throw error, because they require ApplicationContext to be defined on that stage.

You may easily change the code above to get configuration from dynamically built xml, database and any other source.

No comments:

Post a Comment