Last active
December 24, 2015 11:59
-
-
Save blacktaxi/6794494 to your computer and use it in GitHub Desktop.
Ninject ConstructorArguments as named parameters to a dynamic invoke
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Ninject | |
{ | |
public static class NinjectExtensions | |
{ | |
private class DynKernel : DynamicObject | |
{ | |
private readonly IKernel kernel; | |
public DynKernel(IKernel inner) | |
{ | |
this.kernel = inner; | |
} | |
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) | |
{ | |
Contract.Assume(binder.Name == "Get", "Only supporting Get<T>"); | |
var csBinder = binder.GetType().GetInterface( | |
"Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder"); | |
var typeArgs = csBinder.GetProperty("TypeArguments").GetValue(binder, null) | |
as IList<Type>; | |
Contract.Assume(typeArgs != null && typeArgs.Count == 1, | |
"There should be exactly one type parameter to this call"); | |
var typeArg = typeArgs[0]; | |
Contract.Assume( | |
binder.CallInfo.ArgumentCount == binder.CallInfo.ArgumentNames.Count, | |
"All arguments should be named"); | |
var ctorArgs = args.Zip(binder.CallInfo.ArgumentNames, | |
(v, k) => new ConstructorArgument(k, v)).Cast<IParameter>().ToArray(); | |
result = this.kernel.Get(typeArg, ctorArgs); | |
return true; | |
} | |
} | |
public static dynamic AsDynamic(this IKernel k) | |
{ | |
return new DynKernel(k); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment