I am looking for a way to add an interface implementation to a class at runtime. Here is a sample code, which I will discuss below.
Public Interface IAction
Sub DoThis(a As Integer)
End Interface
Class Actor
Implements IAction
Private mNumber As Integer
Public Sub New(number As Integer)
mNumber = number
End Sub
Public Sub DoThis(a As Integer) Implements IAction.DoThis
Console.WriteLine(String.Format("Actor #{0}: {1}", mNumber, a))
End Sub
End Class
Class ActionDispatcher
Implements IAction
Private Shared mActionList As New List(Of IAction)
Public Shared Sub Add(actor As IAction)
mActionList.Add(actor)
End Sub
Public Sub DoThis(a As Integer) Implements IAction.DoThis
For Each act In mActionList
act.DoThis(a)
Next
End Sub
End Class
Module Module1
Sub Main()
Dim a As New ActionDispatcher
ActionDispatcher.Add(New Actor(1))
ActionDispatcher.Add(New Actor(2))
a.DoThis(5)
End Sub
End Module
This is related to WCF, where one needs to provide to CreateHost a single class, which implements all interfaces required for the end points. In this scenario, ActionDispatcher is such a class, and IAction is one of the many interfaces to be implemented.
My vision is to avoid implementing IAction in ActionDispatcher manually, but have some sort of registration mechanism, where I can say, that ActionDispatcher must implement interfaces IAction, IDoing, INoAction, etc - and have the dispatching methods generated for me.
MSDN says, that any class is compatible with any interface, so I don't need to declare "Implements" in the ActionDispatcher. But I still need to implement the interface and connect the implementing method to the interface definition, so WCF can find it when needed.
The closest thing I found is probably the Automatic Interface Implementer, but it (1) creates a new type, (2) adds dummy methods.
I has also tried to understand CodeCompileUnit class, but so far couldn't see the relation to what I need.
Can someone more experienced in Reflection API help me out? Is there a nice way to do whay I want?