Skip to content

Instantly share code, notes, and snippets.

@jbogard
Created January 12, 2015 17:05
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 jbogard/ee8084b79d4f9faf2eb3 to your computer and use it in GitHub Desktop.
Save jbogard/ee8084b79d4f9faf2eb3 to your computer and use it in GitHub Desktop.
public class ContravariantBindingResolver : NinjectComponent, IBindingResolver
{
/// <summary>
/// Returns any bindings from the specified collection that match the specified service.
/// </summary>
public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
{
if (service.IsGenericType)
{
var genericType = service.GetGenericTypeDefinition();
var genericArguments = genericType.GetGenericArguments();
if (genericArguments.Count() == 1
&& genericArguments.Single().GenericParameterAttributes.HasFlag(GenericParameterAttributes.Contravariant))
{
var argument = service.GetGenericArguments().Single();
var matches = bindings.Where(kvp => kvp.Key.IsGenericType
&& kvp.Key.GetGenericTypeDefinition().Equals(genericType)
&& kvp.Key.GetGenericArguments().Single() != argument
&& kvp.Key.GetGenericArguments().Single().IsAssignableFrom(argument))
.SelectMany(kvp => kvp.Value);
return matches;
}
}
return Enumerable.Empty<IBinding>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment