0

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

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305
  • 1
    What about [this](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface) and [this](http://stackoverflow.com/questions/607178/how-enumerate-all-classes-with-custom-class-attribute). These questions has been asked numerous times. – Patrick Hofman Jun 22 '15 at 08:30
  • Couldn't you use [is](https://msdn.microsoft.com/en-us/library/scekt9xw.aspx) for this? – DGibbs Jun 22 '15 at 08:39
  • @DGibbs thanks but `is` operator does not apply. I don't have instances of the classes in my method, I will instantiate the correct class based on the value of an attribute. – usr-local-ΕΨΗΕΛΩΝ Jun 22 '15 at 08:46

1 Answers1

2

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.

Botz3000
  • 39,020
  • 8
  • 103
  • 127