Skip to content

Instantly share code, notes, and snippets.

@pushrbx
Last active August 29, 2015 14:22
Show Gist options
  • Save pushrbx/4d72ed886c227fdb4d2f to your computer and use it in GitHub Desktop.
Save pushrbx/4d72ed886c227fdb4d2f to your computer and use it in GitHub Desktop.
Spring.NET - Merge two application contexts.
public static void MergeWith(this AbstractApplicationContext targetContext,
AbstractApplicationContext sourceContext)
{
Check.NotNull(sourceContext, "sourceContext");
targetContext.Stop();
foreach (var definitionName in sourceContext.GetObjectDefinitionNames())
{
var definition = sourceContext.GetObjectDefinition(definitionName);
targetContext.RegisterObjectDefinition(definitionName, definition);
var obj = targetContext.CreateObject(definitionName, definition.ObjectType,
(from holder in
(from DictionaryEntry val in definition.ConstructorArgumentValues.IndexedArgumentValues
select val.Value).OfType<ConstructorArgumentValues.ValueHolder>()
let typedStr = new TypedStringValue((string) holder.Value, holder.Type)
let type = typedStr.ResolveTargetType()
let typeConverter = TypeConverterRegistry.GetConverter(type)
select typeConverter.ConvertFrom(holder.Value)).ToArray());
targetContext.ConfigureObject(obj, definitionName);
targetContext.GetObject(definitionName);
}
targetContext.Start();
}
// after a merge it's recommended to dispose the old/source context
public static void MergeWith(this IApplicationContext targetContext, IApplicationContext sourceContext)
{
Check.NotNull(sourceContext, "sourceContext");
var absSourceContext = sourceContext as AbstractApplicationContext;
var absTargetContext = targetContext as AbstractApplicationContext;
if (absSourceContext == null || targetContext == null)
return;
absTargetContext.MergeWith(absSourceContext);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment