zenject

How do I create factories capable of multiple parameters with Zenject?


How do I create a factories with zenject with multiple parameter overloaded Create methods (or how to solve this problem differently)?

I want to be able to

var x = factory.Create("bla bla");//string
x = factory.Create();//parameterless
x = factory.Create(1);//int
x = factory.Create(1,2);//int,int
x = factory.Create("bla bla",2);//string,int

Solution

  • One way would be to create a factory that includes the maximum number of parameters and then supply extra methods that use default values for the missing values like this:

    public class Foo
    {
        [Inject]
        public string Value1;
    
        [Inject]
        public int Value2;
    
        public class Factory : Factory<string, int, Foo>
        {
            public Foo Create(string value1)
            {
                return Create(value1, 0);
            }
    
            public Foo Create()
            {
                return Create("default");
            }
        }
    }