I’m using Unity for interception. Because I have many interfaces I’m forced to using VirtualMethodInterceptor. In my behavior I would like to react only when the method called was declared in the particular type of interfaces (with special attribute). I thought that MethodBase.DeclaringType will solve my problem but it behaves different than I was hoping to. It returns implementing type.
I can agree that it makes sense as the method can be declared in multiple interfaces but there should be a way to easily get the list of them. Unfortunately I haven’t found it yet.
Small sample showing my problem
public interface ISample
{
void Do();
}
public class Sample : ISample
{
public void Do()
{
}
}
class Program
{
static void Main(string[] args)
{
var m = typeof(Sample).GetMethod("Do") as MethodBase;
Console.WriteLine(m.DeclaringType.Name); // Prints "Sample"
}
}
one awkward solution:
var interfaces = from i in input.MethodBase.DeclaringType.GetInterfaces()
where i.GetCustomAttributes(typeof(CustomAttribute), true).Length > 0
where i.GetMethod(input.MethodBase.Name, input.MethodBase.GetParameters().Select(p=>p.ParameterType).ToArray()) != null
select i;
The only solution I could come up with (similar to you not-so-awkward solution though).