Get object by attribute value

614 views Asked by At

I have a set of classes which implement a common interface and are annotated with a business domain attribute. By design, each class is annotated with different parametrization

[Foo(Bar=1)]
public class EntityA : ICustomInterface

[Foo(Bar=2)]
public class EntityB : ICustomInterface

[Foo(Bar=3)]
public class EntityC : ICustomInterface

Either From the Spring's IApplicationContext or using plain old reflection, how do I find the class that implements ICustomInterface and is annotated with [Foo(Bar=Y)]?

Something like Spring for Java's getBeansWithAnnotation. I don't require Spring.net, because those objects are prototypes. To be clear: if my task does not require using Spring at all I am happy with that

1

There are 1 answers

0
Botz3000 On BEST ANSWER

If you have obtained the Assembly, you can just iterate over the types and check for your conditions:

var matchingTypes = 
    from t in asm.GetTypes()
    where !t.IsInterface && !t.IsAbstract
    where typeof(ICustomInterface).IsAssignableFrom(t)
    let foo = t.GetCustomAttribute<FooAttribute>()
    where foo != null && foo.Bar == Y
    select t;

I am assuming you want only classes where Foo.Bar has the value Y.