Skip to content

Factory is matching argument names in dependent constructors and causing InvalidCastException #45

@DavidJFowler

Description

@DavidJFowler

In the following example, the factory tries to construct an instance of Class2 passing the argument "argumentA" of type IClass1 passed to the factory method to Class2's constructor instead of using the binding rule to create an instance of Class3. This throws an invalid cast exception.

If I change the name of the constructor argument of Class2 to "ArgumentB" the code works.

Ninject.Extension.Factory v3.3.2
Ninject v3.3.4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject;
using Ninject.Extensions.Factory;

namespace ConsoleApp19
{
    class Program
    {
        static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IClass1>().To<Class1>();
            kernel.Bind<IClass2>().To<Class2>();
            kernel.Bind<IClass3>().To<Class3>();
            kernel.Bind<IClass4>().To<Class4>();
            kernel.Bind<IClass4Factory>().ToFactory();

            var factory = kernel.Get<IClass4Factory>();
            var class1 = kernel.Get<IClass1>();

            // fails with exception Unable to cast object of type 'ConsoleApp19.Class1' to type 'ConsoleApp19.IClass3'
            var class4 = factory.CreateInstance(class1);
        }
    }

    public interface IClass1
    {

    }
    public class Class1 : IClass1
    {
    }

    public interface IClass2
    {

    }
    public class Class2 : IClass2
    {
        public Class2(IClass3 argumentA)
        {

        }
    }

    public interface IClass3
    {

    }

    public class Class3 : IClass3
    {

    }

    public interface IClass4
    {

    }

    public interface IClass4Factory
    {
        IClass4 CreateInstance(IClass1 argumentA);
    }

    public class Class4 : IClass4
    {
        public Class4(IClass1 argumentA, IClass2 class2)
        {

        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions