This is the last of the ‘Unity’ series and I’ll be talking about generics here.
If you’ve been following the previous articles, you must have noticed that I’m just adding more and more ‘Product’ classes to the project. I’ll change that trend in this blog where I’ll be adding an ICaller interface and a Caller class.
We’ll fill-in the implementation of the CallMethod in a few, but first, here’s what we’re going to do:
- create an instance of the Caller class
- pass it the IProduct as a generic parameter
- in the CallMethod method, we’ll use Unity to dynamically create an instance of IProduct implemented object
I need to add the config information for ICaller and Caller types.
The .NET Framework’s convention to express generic types is ICaller`1, where the digit following the "`" matches the number of types contained in the generic type. So a generic type that contains 4 types contained in the generic type would be declared as:
On my .aspx page, I have the following UI design:
Things to note here are that all these radio buttons belong to the same GroupName => only one of these four can be clicked. Next, all four controls postback to the same ‘OnCheckedChanged’ event and lastly the ID’s point to named types of IProduct (already added to the web.config file).
In my calling code, I see which radio button was clicked, pass that as an argument to the CallMethod method.
What’s basically happening here is that the ID of the control gets passed on to the typeName which will be one of “LegacyProduct”, “NewProduct”, “ComplexProduct” or “ArrayConstructor”. I then create an instance of an ICaller and pass the typeName to it.
Now, we’ll fill in the blank for the CallMethod method (sorry for the naming guys).
This is where I’ll resolve the IProduct by passing the type name and calling the WriteProductDetails() method. With all things in place, when I run the application and choose different radio buttons, the output should look something like below:
Basically this is how generics come to play in Unity. Please see the code I’ve used for this here.
This marks the end of the ‘Unity’ series. I’ll definitely post any updates that I find, but for now I don’t have anything planned.