TypeInitializationException 使用 NCrawler;缺少 Autofac 方法

TypeInitializationException using NCrawler; missing Autofac method


我正在用 NCrawler 做一些测试并得到这个奇怪的异常:

The type initializer for 'NCrawler.NCrawlerModule' threw an exception. The inner Exception is: Method not found: 'Void Autofac.RegistrationExtensions.RegisterModule(Autofac.ContainerBuilder, Autofac.Core.IModule)'.

爬虫构造函数出现异常

这是我的代码:

 static void Main(string[] args)
    {
        using (Crawler c = new Crawler(new Uri("http://whosebug.com"), new HtmlDocumentProcessor(), new TestStep()))
        {
            c.MaximumThreadCount = 3;
            c.MaximumCrawlDepth = 2;
            c.ExcludeFilter = new[] { new RegexFilter(
            new Regex(@"(\.jpg|\.css|\.js|\.gif|\.jpeg|\.png|\.ico)",
            RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)) };
            c.Crawl();
        }
    }

这是测试步骤 class:

public class TestStep : IPipelineStep
{
    public void Process(Crawler crawler, PropertyBag propertyBag)
    {
        Console.Out.WriteLineAsync(propertyBag.Step.Uri.ToString());
    }
}

我尝试使用 NuGet 卸载并重新安装 Autofac,但没有成功。 奇怪的是 packages.config 上的版本是 3.5.2 但在 app.config 上它似乎试图将它绑定到 3.5.0
这是 packages.config 中的 AutoFac:

 <package id="Autofac" version="3.5.2" targetFramework="net452" />

并在 app.config 中:

<dependentAssembly>
    <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
  </dependentAssembly>

有人可以帮忙吗?

TypeInitializationException 表示某处的静态构造函数失败。在这种情况下,NCrawlerModule 上的静态构造函数失败。这是开始寻找的地方。

整个 NCrawler 项目看起来一团糟。

所有这一切的关键在于,您可能需要使用 dotPeek 或您最喜欢的反编译器对您正在使用的 的 NCrawler 程序集进行一些探索 看看你有什么。从问题或所有副本和不一致之处来看,这并不明显。

总之,看着the static constructor on NCrawlerModule you see it is, in fact, eventually trying to call a RegisterModule() extension method

现在,looking at Autofac.RegistrationExtensions in Autofac 3.5.2, sure enough, there is no RegisterModule method. In 3.5.2, that method is in a ModuleRegistrationExtensions class,这就是您看到异常的原因:NCrawler 在错误的地方查找。

归结起来就是 您可能有一个针对 Autofac 2.4.5 编译的 NCrawler 版本并且您正在尝试使用 Autofac 3.x .或者,至少,您拥有 NCrawler,并且您正在尝试使用 某些版本 的 Autofac,但该版本的 NCrawler 不兼容。

如果 NuGet 包正确指定了它所使用的版本,您可能可以避免这个问题,但是,同样,该项目似乎有些混乱。

同样,您可以通过查看 NCrawler 程序集的反编译版本并检查它引用的内容来验证所有这些。我猜这是一个很旧的 Autofac 版本。

你有两种选择来解决这个问题。

  • 获取针对更新的 Autofac 编译的新版本 NCrawler。你可以说服那些项目维护者更新他们的包,或者你可以 fork 并自己做。
  • 您可以找出您的 NCrawler 使用的是哪个旧版本的 Autofac,然后将您的整个应用回滚到旧的 Autofac。这对我来说听起来很痛苦,因为你会回到过去。我个人更喜欢尝试让事情向前发展。

此外,希望现在您知道当您将来看到这些异常时应该开始查看什么:从静态构造函数开始,不要害怕开始在第三方源中进行 spelunking。