Created
January 12, 2015 17:05
-
-
Save jbogard/ee8084b79d4f9faf2eb3 to your computer and use it in GitHub Desktop.
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
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