Dan
Dan

Reputation: 29365

"A registration already exists for URI" when using HttpSelfHostServer

We are having an issue unit test failing because previous tests haven't closed session of HttpSelfHostServer.

So the second time we try to open a connection to a sever we get this message:

System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'. 

This test forces the issue (as an example):

 [TestFixture]
    public class DuplicatHostIssue 
    {
    public HttpSelfHostServer _server;

    [Test]
    public void please_work()
    {
        var config = new HttpSelfHostConfiguration("http://localhost:1337/");
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync().Wait();

        config = new HttpSelfHostConfiguration("http://localhost:1337/");
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync().Wait();
    }
}

So newing up a new instance of the server dosent seem to kill the previous session. Any idea how to force the desposal of the previous session?

Full exception if it helps?

      System.AggregateException : One or more errors occurred.   ----> System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'.    
    at 

System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait()    
at ANW.API.Tests.Acceptance.DuplicatHostIssue.please_work() in DuplicatHostIssue.cs: line 32
    --InvalidOperationException    
at System.Runtime.AsyncResult.End(IAsyncResult result)    
at System.ServiceModel.Channels.CommunicationObject.EndOpen(IAsyncResult result) 
at System.Web.Http.SelfHost.HttpSelfHostServer.OpenListenerComplete(IAsyncResult result)

Upvotes: 1

Views: 949

Answers (1)

Darshana
Darshana

Reputation: 594

You might want to write a Dispose method like below and call it appropriately to avoid this issue

private static void HttpSelfHostServerDispose()
{
    if (server != null)
    {
        _server.CloseAsync().Wait();
        _server.Dispose();
        _server = null;
    }
}

This will clear the URI register.

Upvotes: 1

Related Questions