Simon Woods
Simon Woods

Reputation: 2241

CreateDelegate on Interface method

I'm struggling to see where I am going wrong wrt creating a delegate to an interface method

My code is as follows:

private static Func<HtmlDocument, IObservable<IData>> FindScrapeMethod(ICrawlerStrategy crawler, string scrapeDelegate)
{
    Func<HtmlDocument, IObservable<IData>> action;
    var fullDelegateName = String.Format("ICrawlerStrategy.{0}", scrapeDelegate);

    if (!_delegateCache.TryGetValue(fullDelegateName, out action))
    {                
        var method = typeof(ICrawlerStrategy).GetMethod(scrapeDelegate, BindingFlags.Public | BindingFlags.Instance );

        action = (Func<HtmlDocument, IObservable<IData>>)
                    Delegate.CreateDelegate(typeof(Func<HtmlDocument, IObservable<IData>>), crawler, method);
        _delegateCache.Add(fullDelegateName, action);               
    }

    return action;
}

The interface declaration is

public interface ICrawlerStrategy 
{        
    Func<HtmlDocument, IObservable<IData>> ExtractorAsync();
}

The implementing class is as follows

public class MyCrawler : ICrawlerStrategy
{

    <snip>

    Func<HtmlDocument, IObservable<IData>> ICrawlerStrategy.ExtractorAsync()
    {
        return (doc) => AsyncScraper(doc); 
    }
}

Edit1 - as requested by @Yahia:

public IObservable<IData> AsyncScraper(HtmlDocument page)

When trying to create the delegate I'm getting an "Error binding to target method". When I step the code,

  1. the method is not null so it can obviously find the method on the type
  2. the instance is also not null as well

Any pointers, pls.

Thx

S

Upvotes: 3

Views: 380

Answers (1)

Corey Kosak
Corey Kosak

Reputation: 2625

Your problem is in the type that you pass to CreateDelegate.

The return value of your function is

Func<HtmlDocument, IObservable<IData>>

Therefore the type of your delegate is

Func<Func<HtmlDocument, IObservable<IData>>>

So change this line (you'll have to fix others as well to match)

action = (Func<Func<HtmlDocument, IObservable<IData>>>)
          Delegate.CreateDelegate(typeof(Func<Func<HtmlDocument, IObservable<IData>>>), crawler, method);

Upvotes: 7

Related Questions