Skip to content

Generic vs non-generic ResolutionExtension.TryGet overloads are inconsistent #378

@lord-executor

Description

@lord-executor

Run the following code in RoslynPad or in a simple .NET console application with minor adaptations.

#r "nuget:Ninject/3.3.4"

using Ninject;

interface IWarrior {}

class Paladin : IWarrior {}

var kernel = new StandardKernel();
kernel.Bind<IWarrior>().To<Paladin>();
kernel.Bind<IWarrior>().To<Paladin>();

kernel.TryGet<IWarrior>(meta => true).Dump(); // works; returns null
kernel.TryGet(typeof(IWarrior), meta => true).Dump(); // fails; throws InvalidOperationException

To be precise, the exception is:

InvalidOperationException: Sequence contains more than one element
   at System.Linq.ThrowHelper.ThrowMoreThanOneElementException()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at Ninject.ResolutionExtensions.TryGet[T](Func`1 iterator)
   at Ninject.ResolutionExtensions.TryGet(IResolutionRoot root, Type service, Func`2 constraint, IParameter[] parameters)

The only difference in the two calls is that one uses the generic version TryGet<T> while the other does not.

The problem lies in the different parameters to GetResolutionIterator in

To me, this seems very obviously incorrect and from the code in TryGet which explicitly catches an ActivationException, the case seems quite clear: all overloads of TryGet should pass true for isUnique. That way, the method behaves as expected and just returns null if it cannot resolve the request to a uniquely defined service.

I have not actually tested this, but from looking at the source code of the current master branch, I would say the problem exists there as well.

I can easily provide a PR for a fix, but it seems that there is really not a lot of activity on this project at the moment. If any one of the maintainers of this project is at least reading this, please give a sign.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions