Autofac 和南希

Autofac and Nancy

以下结合使用 Autofac 和 Nancy 的程序无法正确启动默认的 Nancy 服务器。

using Autofac;
using Nancy.Hosting.Self;
using System;

namespace NancyExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new NancyHost(new Uri("http://localhost:8080"))).SingleInstance();

            using (var container = builder.Build())
            {
                NancyHost host = container.Resolve<NancyHost>();

                // this fails with:
                // Exception thrown: 'System.Net.HttpListenerException' in System.dll
                // Exception thrown: 'System.Net.HttpListenerException' in System.dll
                // Exception thrown: 'System.InvalidOperationException' in System.dll
                // Exception thrown: 'System.InvalidOperationException' in System.dll

                // this works:
                // NancyHost host = new NancyHost(new Uri("http://localhost:8080"));

                host.Start();
            }

            Console.ReadLine();
        }
    }
}

通过 Autofac 解析 NancyHost 时,.NET 的 HttpListener 中似乎出现了一个错误。似乎没有关于此异常的详细信息。访问 http://localhost:8080 结果没有连接。

我自己实例化 NancyHost 工作正常。

使用:

因为您的代码 "is waiting" 在 Console.ReadLine(); 上并且它在 using 之外,所以 Autofac 容器已经被处理掉了。将 Console.ReadLine(); 移到 using 内使其生效。