Christian Weyer: Smells like service spirit

What's first?

Programatically register SoapExtensions

When I want to use a SoapExtension in order to enhance my Web Service's or Web Service client's capabilities - do I always have to put the configuration in a config file? Isn't there a way to do this (perhaps temporarily) programmatically? Yep, there is. You can get your hands on System.Web.Services.Configuration.WebServicesConfiguration in your own code by using reflection. Take a look at the follwing snippet which injects a specific SoapExtension into the pipeline. Note that there must be a known type TraceExtension present in this context:

static void InjectTraceExtensionToConfig()
{
  Assembly assBase;
  Type webServiceConfig;
  object currentProp;
  PropertyInfo propInfo;
  object[] value;
  Type myType;
  object[] objArray;
  object myObj;
  FieldInfo myField;

  try
  {
    assBase = typeof(SoapExtensionAttribute).Assembly;
    webServiceConfig = assBase.GetType
      ("System.Web.Services.Configuration.WebServicesConfiguration");

    if (webServiceConfig == null)
      throw new Exception("Error ...");

    currentProp = webServiceConfig.GetProperty("Current").
      GetValue(null, null);
    propInfo = webServiceConfig.GetProperty("SoapExtensionTypes");
    value = (object[])propInfo.GetValue(currentProp, null);
    myType = value.GetType().GetElementType();
    objArray = (object[])Array.
      CreateInstance(myType, (int)value.Length + 1);
    Array.Copy(value, objArray, (int)value.Length);

    myObj = Activator.CreateInstance(myType);
    myField = myType.GetField("Type");
    myField.SetValue(myObj, typeof(TraceExtension));
    objArray[(int)objArray.Length - 1] = myObj;
    propInfo.SetValue(currentProp, objArray, null);
  }
  catch (Exception ex)
  {}
}

Comments

No Comments