ninject / Ninject.MockingKernel

Extension for Ninject aiding testability in Moq, NSubstitute, and FakeItEasy
http://ninject.org/
Other
62 stars 25 forks source link

Func<T> is not auto-resolved #6

Closed kenwarner closed 13 years ago

kenwarner commented 13 years ago
public interface IDependency
{
    bool DoDependencyStuff();
}

public class FuncClass
{
    private Func<IDependency> _dependencyFactory;

    public FuncClass(Func<IDependency> dependencyFactory)
    {
        _dependencyFactory = dependencyFactory;
    }

    public bool DoStuff()
    {
        return _dependencyFactory().DoDependencyStuff();
    }
}

[TestFixture]
public class FuncClassFixture
{
    [Test]
    public void When_FuncDependency_CanBeResolved()
    {
        var kernel = new MoqMockingKernel();

        // uncommenting the below line will make this test pass, but shouldn't the MockingKernel handle it for me?
        // kernel.Bind<Func<IDependency>>()
        //  .ToMethod(c => () => kernel.GetMock<IDependency>().Object);

        var subject = kernel.Get<FuncClass>();

        var result = subject.DoStuff();
    }
}

Here is the exception that is thrown

Error activating IntPtr No matching bindings are available, and the type is not self-bindable. Activation path: 3) Injection of dependency IntPtr into parameter method of constructor of type Func{IDependency} 2) Injection of dependency Func{IDependency} into parameter dependencyFactory of constructor of type FuncClass 1) Request for FuncClass

remogloor commented 13 years ago

That's exactly the behavior I would expect at the moment.Func is not mockable but self bindable so an instance of itself is created but Func's ctor requires a IntPtr which leads to the exception.

It's planned for the next release of Ninject to treat Func as factory creating the returned value using the kernel.