Line data Source code
1 : #region Copyright
2 : // -----------------------------------------------------------------------
3 : // <copyright company="Chinchilla Software Limited">
4 : // Copyright Chinchilla Software Limited. All rights reserved.
5 : // </copyright>
6 : // -----------------------------------------------------------------------
7 : #endregion
8 :
9 : using System;
10 : using System.Runtime.Serialization;
11 : using System.ServiceModel;
12 : using System.ServiceModel.Description;
13 :
14 : namespace Cqrs.Services
15 : {
16 : /// <summary>
17 : /// A factory that creates channels of different types that are used by clients to send messages to variously configured service endpoints.
18 : /// </summary>
19 : /// <typeparam name="TService">The <see cref="Type"/> of service this <see cref="ChannelFactory"/> is for.</typeparam>
20 : public class ServiceChannelFactory<TService> : ChannelFactory<TService>
21 1 : {
22 : /// <summary>
23 : /// Instantiates a new instance of the <see cref="ServiceChannelFactory{TService}"/> class with a specified endpoint configuration name.
24 : /// </summary>
25 : /// <param name="endpointConfigurationName">The configuration name used for the endpoint.</param>
26 1 : public ServiceChannelFactory(string endpointConfigurationName)
27 : : base(endpointConfigurationName)
28 : {
29 : RegisterDataContracts();
30 : AttachDataContractResolver(Endpoint);
31 : }
32 :
33 : /// <summary>
34 : /// Uses <see cref="WcfDataContractResolverConfiguration.GetDataContracts{TService}"/>
35 : /// to find <see cref="DataContractResolver">resolvers</see> to automatically attach to each
36 : /// <see cref="OperationDescription"/> in <see cref="ContractDescription.Operations"/> of <see cref="ServiceEndpoint.Contract"/> of the provided <paramref name="endpoint"/>.
37 : /// </summary>
38 1 : protected virtual void AttachDataContractResolver(ServiceEndpoint endpoint)
39 : {
40 : ContractDescription contractDescription = endpoint.Contract;
41 :
42 : foreach (OperationDescription operationDescription in contractDescription.Operations)
43 : {
44 : Type dataContractType = WcfDataContractResolverConfiguration.Current.GetDataContracts<TService>(operationDescription.Name);
45 : if (dataContractType == null)
46 : continue;
47 : DataContractSerializerOperationBehavior serializerBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
48 : if (serializerBehavior == null)
49 : operationDescription.Behaviors.Add(serializerBehavior = new DataContractSerializerOperationBehavior(operationDescription));
50 : serializerBehavior.DataContractResolver = (DataContractResolver)Activator.CreateInstance(AppDomain.CurrentDomain, dataContractType.Assembly.FullName, dataContractType.FullName).Unwrap();
51 : }
52 : }
53 :
54 : /// <summary>
55 : /// Register any additional <see cref="DataContractResolver">resolvers</see>.
56 : /// </summary>
57 1 : protected virtual void RegisterDataContracts() { }
58 : }
59 : }
|