In the previous article of the series, I talked about constructor and property (setter) injection. I wanted to write about how to work with arrays and generics in Unity in this blog, after seeing how lengthy this one got, I’ve decided to write about generics in the next one. This one will only concentrate on arrays.
My Product4 class has the following definition:
The key parts are line 4 where we declare an array of ILogger and line 5 where-in the constructor passes an instance of an array of ILogger objects.
I’ve created another class – FakeLogger:
It’s implementation is the same as what we had for the FileLogger class. Coming to the web.config file, first add the following aliases. The alias for FakeLogger should make sense right away. ILoggerArray defines an array of ILogger objects. I’ll tell why we need an alias for System.String data type.
Next is to create mappings for the FileLogger and FakeLogger classes:
Finally, for the real deal:
Here’s where I’m saying, that if a type of IProduct is requested to be resolved, map it to type Product4. Furthermore, the Product4 has two constructor parameters – a string and an array of type ILogger. You might have observed the first parameter of the constructor is named ‘productName’ and that matches the value in the name attribute of the param element. The parameterType of ‘string’ maps to ‘System.String, mscorlib’ and is defined in the type alias above.
The set up is similar for the second constructor parameter. The name matches the name of the parameter (loggers) and is of type ILoggerArray, which maps to an array of ILogger objects. We’ve also decided to add two elements to this array when unity resolves it – an instance of FileLogger and one of FakeLogger.
The click event of the button does the following:
It’s worth mentioning here about the change in the format of resolving the IProduct to create an instance of Product4. You cannot use the regular way (the commented lines) to get an instance of Product4. The reason is due to the behavior of Unity which Alex Ermakov has brilliantly explained here.
The corresponding output of the action is:
You have a couple of options when it comes to adding dependency elements in the array node. You can:
- leave it empty (no dependency elements declared): This will only create an empty array of loggers. This way you can check for non-null condition, in your mock classes.
- add multiple dependency elements with the same name
With this you’ll see two instances of FakeLogger in the output. This article shows how Unity allows you to instantiate objects with arrays. Find the code here.