I've done some hideous DI reflection :(
I've gotten a FieldInfo
object and called GetValue()
on it.
I get an object
back.
Examining this object in VisualStudio, I discover that it is a "prototype", and that GetType()
returns System.RuntimeType
.
In the immediate window, I can cast my object as System.RuntimeType
, and then I discover an AsType()
method, which returns me my real, typed object.
Unfortunately, when try to write this in my code, I'm told that System.RuntimeType
is an internal type, and thus I can't use it :(.
How can I get a typed object out of this object?
KernelBase baseKernel = (KernelBase)ninjectKernel;
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = typeof(KernelBase).GetField("bindings", flags);
Multimap<Type, IBinding> allBindingsPerTypeMap = (Multimap<Type, IBinding>)field.GetValue(baseKernel);
var aBinding = allInterfaceTypesWithAllBindings.First(pair => pair.InterfaceType.Name.Contains("FilePath")).Binding;
var aBindingTarget = aBinding .BindingConfiguration.ProviderCallback.Target;
var prototype = aBindingTarget.GetType().GetField("prototype").GetValue(aBindingTarget);
// prototype is an object, which I'd like to turn into a real type.
var runtimeType = prototype.GetType(); // this returns System.RuntimeType
Solutions to the root problem are useful, but I do actually want to know how to interact with this System.RuntimeType
object.
If there's a non-reflection approach, I'd be keen to know it though?
I tend to think that if you're this far down the rabbit hole (or, I suppose, through the looking glass), you should give up any pretence of benefitting from a static type system, and just take advantage of the dynamic runtime (assuming you're on .NET 4 or greater).
See https://blogs.msdn.microsoft.com/davidebb/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code/ for an example of how much tidier the code can be (and a handy 'AsDynamic' extension method to make this easier).