private void AddMetadataServiceBehavior()
{
// Get a pointer to system.serviceModel section.
ConfigurationSectionGroup csg = configuration.SectionGroups["system.serviceModel"];
// Notify if we get a null reference.
Debug.Assert(csg != null, "system.serviceModel section could not be found in the configuration.");
if (csg != null)
{
// Try to find the extensions element.
ExtensionsSection extensionsSection = csg.Sections["extensions"] as ExtensionsSection;
// Create it if it wasn't found.
if (extensionsSection == null)
{
extensionsSection = new ExtensionsSection();
csg.Sections.Add("extensions", extensionsSection);
}
// Now create the new behavior extension.
ExtensionElement metadataServiceExtensionElement = new ExtensionElement();
metadataServiceExtensionElement.Name = "metadataService";
//TODO: Make this more dynamic so it can discover the assembly version etc otherwise this will always throw exceptions
// that the behavior extension was not found in the collection.
metadataServiceExtensionElement.Type = "Thinktecture.ServiceModel.Extensions.Metadata.StaticMetadataBehaviorElement, Thinktecture.ServiceModel.Extensions.Metadata, Version=1.0.14.0, Culture=neutral, PublicKeyToken=20fb7cabbfb92df4";
// Add the newly created behavior extension to the extensions section.
extensionsSection.BehaviorExtensions.Add(metadataServiceExtensionElement);
// Try to find the behaviors element.
BehaviorsSection behaviorsSection = csg.Sections["behaviors"] as BehaviorsSection;
// Create it if it wasn't found.
if (behaviorsSection == null)
{
behaviorsSection = new BehaviorsSection();
csg.Sections.Add("behaviors", behaviorsSection);
}
// Add the new service behavior.
ServiceBehaviorElement serviceBehavior = new ServiceBehaviorElement();
serviceBehavior.Name = "metadataServiceExtension";
behaviorsSection.ServiceBehaviors.Add(serviceBehavior);
StaticMetadataBehaviorElement behaviorExtensionElement = new StaticMetadataBehaviorElement();
behaviorExtensionElement.RootMetadataFileLocation = options.MetadataLocation;
behaviorExtensionElement.MetadataUrl = "wsdl";
serviceBehavior.Add(behaviorExtensionElement);
// Find the service section.
ServicesSection servicesSection = csg.Sections["services"] as ServicesSection;
if (servicesSection != null)
{
string fqServiceTypeName = GetFullyQulifiedTypeName(GetServiceTypeName());
ServiceElement serviceElement = servicesSection.Services[fqServiceTypeName] as ServiceElement;
if (serviceElement != null)
{
serviceElement.BehaviorConfiguration = "metadataServiceExtension";
}
}
}
}