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 然後找到服務名稱 删除掉 電腦重新啟動之後就可以了。