Injection is not happening for parameterized constructor

26 views
Skip to first unread message

krishna...@juegostudio.net

unread,
Aug 7, 2018, 8:14:47 AM8/7/18
to StrangeIoC



Hi, I have binded to object like 

injecitonBinder.Bind<WorldColelction>().Tosingleton().crossconetct();

so while injection it is getting null binding exception because of parameterized constructor. When i add empty constructor then it is working.

How can we provide paramterized constructor ???

Dan Peavey

unread,
Aug 8, 2018, 11:49:37 AM8/8/18
to krishna...@juegostudio.net, StrangeIoC
You should build a factory instead, perhaps. 

1. Remove your current WorldObjectCollection binding.

2. Create a WorldObjectCollectionFactory - it’s job is to provide a Create method that takes the WorldObjectCollection parameters you want.

3. Bind WorldObjectCollectionFactory, and inject this as a singleton instead.

You can easily abstract that further, too. Works great for this injection.

--
You received this message because you are subscribed to the Google Groups "StrangeIoC" group.
To unsubscribe from this group and stop receiving emails from it, send an email to strangeioc+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

wcorwin

unread,
Aug 9, 2018, 3:00:54 PM8/9/18
to StrangeIoC
So... the reason it didn't support this initially is older versions of C# (4? I forget) didn't support optional parameters constructors at all. I'm fine with breaking support with Unity 3.5 or whatever the last version was that had this constraint. I was maintaining a live game that used 3.5 when Strange was released, so it was a meaningful choice at the time. It's throwing a null binding exception because there's no binding, so it's all "working".  Probably not the outcome you wanted! 

If you want a fix right now, just add the optional bit in a default constructor and move on with your day. When selecting which constructor to use, we choose the one with the shortest signature. If you want to default to one with a longer signature, simply give it the [Construct] tag to designate it the preferred constructor. I find it a good habit to tag one constructor if you have multiple, even if it's the shortest and doesn't need the designation.

If you want to look into strange itself for this, check out ReflectionBinder, where we will initially do all of our reflection. mapPreferredConstructor, findPreferrredConstructor. Where we look at the ParameterInfo[], we would need to store the isOptional and/or DefaultValue from ParameterInfo and store those values so we can access them later at injection time (Injector.Instantiate)

Hope that helps!
Reply all
Reply to author
Forward
0 new messages