Line data Source code
1 : using System;
2 : using System.Runtime.Serialization;
3 : using System.ServiceModel.Description;
4 : using Cqrs.Services;
5 : using Ninject.Extensions.Wcf;
6 :
7 : namespace Cqrs.Ninject.ServiceHost
8 : {
9 : /// <summary>
10 : /// A <see cref="NinjectServiceHostFactory"/> suitable for use with WCF.
11 : /// </summary>
12 : /// <typeparam name="TServiceType">The <see cref="Type"/> of the WCF service contract.</typeparam>
13 : public class NinjectWcfServiceHostFactory<TServiceType> : NinjectServiceHostFactory
14 1 : {
15 : /// <summary>
16 : /// Creates a <see cref="System.ServiceModel.ServiceHost"/> for a specified type of service with a specific base address.
17 : /// </summary>
18 : /// <param name="serviceType">Specifies the <see cref="Type"/> of service to host.</param>
19 : /// <param name="baseAddresses">The <see cref="System.Array"/> of type <see cref="System.Uri"/> that contains the base addresses for the service hosted.</param>
20 : /// <returns>A <see cref="System.ServiceModel.ServiceHost"/> for the type of service specified with a specific base address.</returns>
21 1 : protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
22 : {
23 : System.ServiceModel.ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
24 :
25 : foreach (ServiceEndpoint serviceEndpoint in host.Description.Endpoints)
26 : {
27 : foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations)
28 : {
29 : Type dataContractType = WcfDataContractResolverConfiguration.Current.GetDataContracts<TServiceType>(operationDescription.Name);
30 : if (dataContractType == null)
31 : continue;
32 : DataContractSerializerOperationBehavior serializerBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
33 : if (serializerBehavior == null)
34 : operationDescription.Behaviors.Add(serializerBehavior = new DataContractSerializerOperationBehavior(operationDescription));
35 : serializerBehavior.DataContractResolver = (DataContractResolver)Activator.CreateInstance(AppDomain.CurrentDomain, dataContractType.Assembly.FullName, dataContractType.FullName).Unwrap();
36 : }
37 : }
38 :
39 : return host;
40 : }
41 : }
42 : }
|