In this post, I thought of discussing creating proxy via factory where in you don’t want to register the dependency in simplest way like what we usually do.
Above snippet is fairly simple, here I am just creating factory out of that contract and that works fairly well. But, this has got developer’s dependency which means as and when we will be adding new endpoint to our endpoint.config file, this needs to be added here exclusively. Hence, this is kind of manual way of doing, not generic way. However, we can go ahead and automate the same, so that developer’s can skip this process of exclusively registering the same via UnityConfig.cs file. One point to note here, I am using Microsoft Unity as IOC container here. Therefore, in order to get started with generic stuff, below is the sample snippet for the same.
First I am fetching the client section, then I am reading the endpoints and from there, I am constructing the required Assembly on the fly. After that I am loading the required assembly and then I am checking for types and that of interface after that I am checking for servicecontract attribute. Hence, I am exclusively telling consider only those which are marked as [ServiceContract] attribute. With that thing said, its then calling another generic method with that incoming interface.
Then, I have a generic method to take the incoming type and then convert the same as generic and then create the instance out of that.
Here, first I am reading the Type and then converting the same as Generic type. After that, I am fetching the binding collection and address collection and then applying the binding configuration to the corresponding contract and address. After, this I am creating an instance of factory by passing “FactoryType, Binding and Address“. Once the instance got created, then applied client side end point behavior. This is there to make sure that if any context or header info needs to get added before sending it to the server, this will add the info to that.
In the above snippet, we just have methods for reading bindings, endpoints and other stuff. Below is the completed code for the same.
I hope you would have liked this discussion around creating factory out of Reflection and Generic type and registering the same using Unity. This way, we can simply ship the code without any developer dependency on UnityConfig changes.
917 total views, 1 views today