I’m creating instances of a generic type using reflection:
public interface IModelBuilder<TModel>
{
TModel BuildModel();
}
public class MyModel
{
public string Name { get; set; }
}
public class MyModelBuilder : IModelBuilder<MyModel>
{
public MyModel BuildModel()
{
throw new NotImplementedException();
}
}
At runtime all we know is the Type of model e.g. MyModel. I can find instances of the relevant model builder like so:
var modelBuilders = from t in Assembly.GetExecutingAssembly().GetTypes()
from i in t.GetInterfaces()
where i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IModelBuilder<>)
&& i.GetGenericArguments()[0] == modelType
select t;
var builder = Activator.CreateInstance(modelBuilders.First());
But I’m not sure how I can then cast the instance as IModelBuilder<TModel> so I can call and work with the result of BuildModel().
Since
modelTypeis just aTypeinstance, you can’t do that automatically, since there is no non-generic API available. Various options:1: use reflection, for example (untested)
2: cheat with
dynamic:3: make a non-generic version of
IModelBuilder, and use thatNote that 1 & 2 rely on a public implementation of the interface, and will fail for a (perfectly legal) explicit interface implementation. For “1”, you can fix this via:
A final sneaky option is to flip from a non-generic method into a generic method, so inside the generic method you can use all the members directly. There’s a lazy way to do that via
dynamic: