BsonSerializationOptionsAttribute.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. namespace MongoDB.Bson.Serialization.Attributes
  17. {
  18. /// <summary>
  19. /// Abstract base class for serialization options attributes.
  20. /// </summary>
  21. public abstract class BsonSerializationOptionsAttribute : Attribute, IBsonMemberMapAttribute
  22. {
  23. // constructors
  24. /// <summary>
  25. /// Initializes a new instance of the BsonSerializationOptionsAttribute class.
  26. /// </summary>
  27. protected BsonSerializationOptionsAttribute()
  28. {
  29. }
  30. // public methods
  31. /// <summary>
  32. /// Applies a modification to the member map.
  33. /// </summary>
  34. /// <param name="memberMap">The member map.</param>
  35. public virtual void Apply(BsonMemberMap memberMap)
  36. {
  37. var serializer = memberMap.GetSerializer();
  38. var reconfiguredSerializer = Apply(serializer);
  39. memberMap.SetSerializer(reconfiguredSerializer);
  40. }
  41. // protected methods
  42. /// <summary>
  43. /// Reconfigures the specified serializer by applying this attribute to it.
  44. /// </summary>
  45. /// <param name="serializer">The serializer.</param>
  46. /// <returns>A reconfigured serializer.</returns>
  47. /// <exception cref="System.NotSupportedException"></exception>
  48. protected virtual IBsonSerializer Apply(IBsonSerializer serializer)
  49. {
  50. // if none of the overrides applied the attribute to the serializer see if it can be applied to a child serializer
  51. var childSerializerConfigurable = serializer as IChildSerializerConfigurable;
  52. if (childSerializerConfigurable != null)
  53. {
  54. var childSerializer = childSerializerConfigurable.ChildSerializer;
  55. var reconfiguredChildSerializer = Apply(childSerializer);
  56. return childSerializerConfigurable.WithChildSerializer(reconfiguredChildSerializer);
  57. }
  58. var message = string.Format(
  59. "A serializer of type '{0}' is not configurable using an attribute of type '{1}'.",
  60. BsonUtils.GetFriendlyTypeName(serializer.GetType()),
  61. BsonUtils.GetFriendlyTypeName(this.GetType()));
  62. throw new NotSupportedException(message);
  63. }
  64. }
  65. }