Hi All,
I'm new to this forum and I was here recently trying to find an answer for how to use Attribute based configuration for setting up my spring container.
In my lack of luck in finding good examples of how I would do this in Spring.net I created the following scanner that together with CodeConfigApplicationContext does the trick:
Code:
using System;
using Spring.Context.Attributes;
using Spring.Objects.Factory.Support;
using Spring.Stereotype;
namespace AttributeBasedSpringConfig
{
public class AttributeBasedObjectDefinitionScanner : AssemblyObjectDefinitionScanner
{
protected override bool IsCompoundPredicateSatisfiedBy(Type type)
{
var attribute = Attribute.GetCustomAttribute(type, typeof(ComponentAttribute), true);
if (attribute != null)
{
return true;
}
return base.IsCompoundPredicateSatisfiedBy(type);
}
public override void ScanAndRegisterTypes(IObjectDefinitionRegistry registry)
{
IEnumerable<Type> configTypes = base.Scan();
//if we have at least one config class, ensure the post-processor is registered
if (configTypes.Any())
{
AttributeConfigUtils.RegisterAttributeConfigProcessors(registry);
}
foreach (Type type in configTypes)
{
ObjectDefinitionBuilder definition = ObjectDefinitionBuilder.GenericObjectDefinition(type);
registry.RegisterObjectDefinition(GetObjectRegistryName(definition.ObjectDefinition),
definition.ObjectDefinition);
}
}
private string GetObjectRegistryName(AbstractObjectDefinition objectDefinition)
{
var attribute = Attribute.GetCustomAttribute(objectDefinition.ObjectType, typeof (ComponentAttribute), true);
if (attribute != null)
{
var componentName = ((ComponentAttribute) attribute).Name;
if (!String.IsNullOrWhiteSpace(componentName))
{
return componentName;
}
}
return objectDefinition.ObjectTypeName;
}
}
}
You can find a full example with explanation on how I did it in my blog post: Spring.net Attribute Based Configuration
P.S. I'm new to C# (almost 1 month exp) so please forgive me if I'm offending the good practices within the language.