I have a set of classes that inherit from the same base class and I need to create a factory method for instantiation of the different base class implementations based on the GuidAttribute attached to the implementing class. So basically the scenario is like this:
abstract class Foo
{
/* ... */
public static Foo Create(Guid guid) {
Type type;
// Resolve the type ?
return Activator.CreateInstance(type) as Foo;
}
}
[Guid("<guid1>")]
class Bar : Foo { ... }
[Guid("<guid2>")]
class Baz : Foo { ... }
Is there any other way than iterating all the types in the loaded assemblies and caching the results?
It wouldn’t be automatic but you could simply build a
Dictionary<Guid,Type>or if there’s a common interface/class in each assembly (ala plugin architecture) request it register the types accordingly.There’s no need to use reflection for everything 🙂 I find it less elegant in many cases.