Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DavidJFowler opened this issue Nov 29, 2018 · 0 comments

Comments

@DavidJFowler
Copy link

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)
        {

        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant