I use jQuery ajax calls to ASP.Net web services (ASMX files) to update the web page data.
I have the database storing code seperate from the domain object class code (in the example code below, there is an Animal class and an AnimalRepository class). I’m implememting a convention that all similar domain object repository classes will have a Store method .
I would like to create a web service that can cater for calling the Store method for any one of these repository classes. To get this to work, in the below code sample, the List(Of Animal) parameter would need to be a generic type.
I tried a List(Of Object), but the Store command errors on not able to convert types. I don’t think I can cast the List(Of Object) to the right type, as it’s not known until runtime.
<WebMethod(True)> _
Public Sub StoreAnimals(ByVal _animals As List(Of Animal), ByVal _type As String)
Dim classType As Type = Type.GetType(_type & "Repository, MyCompany.Assembly")
Dim instanceOfClass = Activator.CreateInstance(classType)
Dim method As MethodInfo = classType.GetMethod("Store")
method.Invoke(instanceOfClass, New Object() {_animals})
End Sub
Ideally, I would like:
<WebMethod(True)> _
Public Sub StoreData(Of T)(ByVal _data As List(Of T), ByVal _type As String)
Dim classType As Type = Type.GetType(_type & "Repository, MyCompany.Assembly")
Dim instanceOfClass = Activator.CreateInstance(classType)
Dim method As MethodInfo = classType.GetMethod("Store")
method.Invoke(instanceOfClass, New Object() {_data})
End Sub
There’s no room for generics in the webservice method definition, but is there a trick to achieve the same end result.
Otherwise, I’m going to be creating lots of these Store* webservices that only differ on the first parameter.
Generics have no meaning in the web services world.
You can’t come anywhere close to this with ASMX. With WCF, you might be able to do something, but you can’t use an open generic type in an operation contract.