Skip to content

Instantly share code, notes, and snippets.

@blacktaxi
Last active December 24, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacktaxi/6794494 to your computer and use it in GitHub Desktop.
Save blacktaxi/6794494 to your computer and use it in GitHub Desktop.
Ninject ConstructorArguments as named parameters to a dynamic invoke
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