WCF服务自我寄宿 Windows服务
WCF寄宿有自我寄宿跟IIS寄宿
服务代码:
[ServiceContract] ---服务契约 public interface ICustomerService { [OperationContract] string GetCusomerName(string customercode); [OperationContract] Customer GetCustomer(Customer customer); [OperationContract] List<Customer> GetAllCustomerList(); }
public class CustomerService:ICustomerService { public string GetCusomerName(string customercode) { return "惠森药业有限公司"; } public Customer GetCustomer(Customer customer) { return new Customer() { id = 11, CustomerName = "惠森药业有限公司", CusomerAddres = "新疆", CusomerPhone = 1626772323, Remark = "无" }; } public List<Customer> GetAllCustomerList() { List<Customer> cus = new List<Customer>(); cus.Add(new Customer() { id = 11, CustomerName = "惠森药业有限公司", CusomerAddres = "新疆", CusomerPhone = 1626772323, Remark = "无" }); cus.Add(new Customer() { id = 12, CustomerName = "黄河药业有限公司", CusomerAddres = "新疆", CusomerPhone = 1626772323, Remark = "无" }); cus.Add(new Customer() { id = 13, CustomerName = "长江药业有限公司", CusomerAddres = "新疆", CusomerPhone = 1626772323, Remark = "无" }); return cus; } }
//安装类 [RunInstaller(true)] public class ProjectInstaller:Installer { private readonly ServiceProcessInstaller _process; private readonly ServiceInstaller _service; public ProjectInstaller() { _process = new ServiceProcessInstaller { //账户类型 Account = ServiceAccount.LocalSystem }; _service = new ServiceInstaller { //服务名称 ServiceName = "WCF.ServiceHostByWindowService", //服务描述 Description = "WCF服务宿主在WindowService" }; base.Installers.Add(_process); base.Installers.Add(_service); } } /// <summary> /// Windwos服务 /// </summary> public class WindowService : ServiceBase { public ServiceHost serviceHost = null; //服务宿主 public WindowService() { base.ServiceName = "WCF.ServiceHostByWindowService"; } //启动服务 protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } serviceHost = new ServiceHost(typeof(WCFHostSelf.CustomerService)); serviceHost.Open(); // serviceHost.Opening+= base.OnStart(args); } //停止服务 protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } base.OnStop(); } //运行 public static void Run() { ServiceBase.Run(new WindowService()); } }
控制台程序:
class Program { static void Main(string[] args) { WindowService ser = new WindowService(); WindowService.Run(); } }
然后以管理员运行命令窗口:
然后运行:如果出现下面的效果 运行成功了
然后到系统服务中去查找服务:
然后启动服务。服务启动之后在VS里添加服务引用:
WCF 寄宿到Window服务完成了。。、
在注册表删除服务:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services 然后找到服务名称 删除掉 电脑重新启动之后就可以了。