0
votes

The following program using Autofac in conjunction with Nancy does not launch the default Nancy server correctly.

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();
        }
    }
}

When resolving NancyHost via Autofac, it appears that an error comes deep within .NET's HttpListener. There doesn't seem to be good details on this exception. Visiting http://localhost:8080 results in no connection.

Instantiating NancyHost myself works fine.

Using:

  • Autofac 4.3
  • Nancy 1.4.3
  • Nancy.Hosting.Self 1.4.1
1
Why would you resolve the NancyHost from the container? It's not using the container at all? - khellang
Also, I'm not sure why that call would fail with anything related to HttpListener. Nancy doesn't even touch HttpListener before calling Start. - khellang
I've simplified the use case just to demonstrate the problem. In reality I would inject configuration from the container. The errors I listed are actually when Start is called. - Kevin Deenanauth

1 Answers

2
votes

Because your code "is waiting" on Console.ReadLine(); and it is outside the using, the Autofac container is already disposed . Move Console.ReadLine(); inside using to make it work.