您可以使用自定义引导程序将其拆分为每个服务器的单独项目,以分离 NancyModule 注册。
这个例子是一个三部分的解决方案,每个服务器有两个类库和一个控制台应用程序来启动它们。
第一个服务器项目
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Hosting.Self;
namespace Server1
{
public class Server : NancyModule
{
private static NancyHost _server;
public static void Start()
{
_server = new NancyHost(new Bootstrapper(), new Uri("http://localhost:8686"));
_server.Start();
}
public Server()
{
Get["/"] = _ => "this is server 1";
}
}
public class Bootstrapper : DefaultNancyBootstrapper
{
/// <summary>
/// Register only NancyModules found in this assembly
/// </summary>
protected override IEnumerable<ModuleRegistration> Modules
{
get
{
return GetType().Assembly.GetTypes().Where(type => type.BaseType == typeof(NancyModule)).Select(type => new ModuleRegistration(type, this.GetModuleKeyGenerator().GetKeyForModuleType(type)));
}
}
}
}
第二个服务器项目
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Hosting.Self;
namespace Server2
{
public class Server : NancyModule
{
private static NancyHost _server;
public static void Start()
{
_server = new NancyHost(new Bootstrapper(), new Uri("http://localhost:9696"));
_server.Start();
}
public Server()
{
Get["/"] = _ => "this is server 2";
}
}
public class Bootstrapper : DefaultNancyBootstrapper
{
/// <summary>
/// Register only NancyModules found in this assembly
/// </summary>
protected override IEnumerable<ModuleRegistration> Modules
{
get
{
return GetType().Assembly.GetTypes().Where(type => type.BaseType == typeof(NancyModule)).Select(type => new ModuleRegistration(type, this.GetModuleKeyGenerator().GetKeyForModuleType(type)));
}
}
}
}
从单独的控制台应用程序或其他任何方式启动它们
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Server1.Server.Start();
Server2.Server.Start();
Console.WriteLine("servers started...");
Console.Read();
}
}
}