Я реализую и службу WCF Async, используя привязку WsDualHttpBinding для дуплексной связи для получения изменений в базе данных.Асинхронный вызов WCF с использованием дуплексной связи для получения изменения базы данных
Я внедрил Сервис, но я не знаю, как его вызвать из клиентского приложения.
Вот код.
Ниже код служба WCF
[ServiceContract()]
public interface ICustomerService
{
[OperationContract(IsOneWay = true)]
void GetAllCustomer();
}
public interface ICustomerServiceCallback
{
[OperationContract(IsOneWay = true)]
void Callback(Customer[] customers);
}
[ServiceContract(Name = "ICustomerService",
CallbackContract = typeof(CustomerServiceLibrary.ICustomerServiceCallback),
SessionMode = SessionMode.Required)]
public interface ICustomerServiceAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetAllCustomer(AsyncCallback callback, object asyncState);
void EndGetAllCustomer(IAsyncResult result);
}
[DataContract]
public class Customer
{
[DataMember]
public string Name
{
get;
set;
}
}
}
public class CustomerService :ICustomerService,IDisposable
{
List<Customer> Customers = null;
ICustomerServiceCallback callback;
Customer customer = null;
string constr = "Data Source=.;Initial Catalog=WPFCache;Persist Security Info=True;User ID=sa;Password=Password$2";
public CustomerService()
{
callback = OperationContext.Current.GetCallbackChannel<ICustomerServiceCallback>();
SqlDependency.Start(constr);
}
public void GetAllCustomer()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "GetHero";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
// Create the associated SqlDependency
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
SqlDataReader dr = cmd.ExecuteReader();
Customers = new List<Customer>();
while (dr.Read())
{
customer = new Customer();
customer.Name = dr.GetString(0);
Customers.Add(customer);
}
}
callback.Callback(Customers.ToArray());
}
}
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
try
{
if (e.Type == SqlNotificationType.Change)
{
GetAllCustomer();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
SqlDependency.Stop(constr);
}
}
Я принимал это WCF Async службы, как сам хостинг в консольном приложении.
Здесь хостинг код
класс Программа {
static void Main(string[] args)
{
StartService();
}
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
Uri httpbaseAddress = new Uri("http://localhost:8087/CustomerService/");
Uri[] baseAdresses = { httpbaseAddress };
myServiceHost = new ServiceHost(typeof(CustomerServiceLibrary.CustomerService));
myServiceHost.AddServiceEndpoint(typeof(CustomerServiceLibrary.ICustomerService), new WSDualHttpBinding(), httpbaseAddress);
ServiceDescription serviceDesciption = myServiceHost.Description;
foreach (ServiceEndpoint endpoint in serviceDesciption.Endpoints)
{
Console.WriteLine("Endpoint - address: {0}", endpoint.Address);
Console.WriteLine(" - binding name:\t\t{0}", endpoint.Binding.Name);
Console.WriteLine(" - contract name:\t\t{0}", endpoint.Contract.Name);
Console.WriteLine();
}
myServiceHost.Open();
Console.WriteLine("Press enter to stop.");
Console.ReadKey();
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
В клиентском приложении уже упаковали заводской экземпляр DuplexChannel Вот код.
private void Window_Loaded(object sender, RoutedEventArgs e) { EndpointAddress address = new EndpointAddress(new Uri("http://localhost:8087/CustomerService")); WSDualHttpBinding wsDualBinding = new WSDualHttpBinding(); DuplexChannelFactory<ICustomerServiceAsync> client = new DuplexChannelFactory<ICustomerServiceAsync>(new InstanceContext(this), wsDualBinding, address); App.channel = client.CreateChannel();
}
Теперь мой вопрос, как я могу назвать
- BeginGetAllCustomer
- EndGetAllCustomer
метод моей службы.
Помощь мне .... Большое спасибо заранее ...