/// <summary> /// 指定宿主机环境 /// </summary> /// <param name="hostBuilder"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="token"></param> /// <returns></returns> public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder, string address, int port, string token = "True") { return(hostBuilder.MapServices(mapper => { BuildServiceEngine(mapper); mapper.Resolve <IServiceCommandManager>().SetServiceCommandsAsync(); var serviceToken = mapper.Resolve <IServiceTokenGenerator>().GeneratorToken(token); var _port = AppConfig.ServerOptions.Port == 0 ? port : AppConfig.ServerOptions.Port; var _address = AppConfig.ServerOptions.Ip ?? address; var _ip = AddressHelper.GetIpFromAddress(_address); _port = AppConfig.ServerOptions.IpEndpoint?.Port ?? _port; _ip = AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip; if (_ip.IndexOf(".") < 0 || _ip == "" || _ip == "0.0.0.0") { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet && (_ip == "" || _ip == "0.0.0.0" || _ip == adapter.Name)) { IPInterfaceProperties ipxx = adapter.GetIPProperties(); UnicastIPAddressInformationCollection ipCollection = ipxx.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { _ip = ipadd.Address.ToString(); } } } } } var mappingIp = AppConfig.ServerOptions.MappingIP ?? _ip; var mappingPort = AppConfig.ServerOptions.MappingPort; if (mappingPort == 0) { mappingPort = _port; } if (string.IsNullOrEmpty(AppConfig.ServerOptions.MappingIP)) { ConfigureRoute(mapper, _ip, _port, serviceToken); } else { ConfigureRoute(mapper, _ip, _port, mappingIp, mappingPort, serviceToken); } //初始化模块 mapper.Resolve <IModuleProvider>().Initialize(); //获取微服务主机(可能存在多个运行时主机,取决于微服务依赖的模块) var serviceHosts = mapper.Resolve <IList <Runtime.Server.IServiceHost> >(); Task.Factory.StartNew(async() => { foreach (var serviceHost in serviceHosts) { await serviceHost.StartAsync(_ip, _port); } mapper.Resolve <IServiceEngineLifetime>().NotifyStarted(); }).Wait(); })); }