I'm trying to dynamically create an instance of a type which inherits from a generic interface
.
For example I have the following base-interface, where several other interfaces are derived from:
public interface IDummy { }
And I have two derived interfaces:
public interface IDummyDerived<T> : IDummy
{
void Foo(T value);
}
public interface ITempDerived<T> : IDummy
{
void HelloWorld(T value);
}
Now I need a ServiceProvider-Class where I can create find the classes which implementing the given interface. Each interface (IDummyDerived and ITempDerived) is implemented exactly once.
My approach would be:
internal class DummyServiceProvider
{
public T GetDummy<T>() where T : IDummy
{
Type baseType = typeof(IDummy);
Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(p => baseType.IsAssignableFrom(p) && p.IsClass).ToArray();
//now I have all classes which implements one of my interfaces
foreach(Type type in types)
{
// here I want to check if the current type is typeof(T)
// (typeof(T) == type) -> doesn't work
// (type.GetGenericTypeDefinition() == type) doesnt work
}
}
return default(T);
}
How can I correctly compare the given typeof(T)
to a type in the types-array?
Aucun commentaire:
Enregistrer un commentaire