BsonDictionaryOptionsAttribute.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. using MongoDB.Bson.Serialization.Options;
  17. namespace MongoDB.Bson.Serialization.Attributes
  18. {
  19. /// <summary>
  20. /// Specifies serialization options for a Dictionary field or property.
  21. /// </summary>
  22. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
  23. public class BsonDictionaryOptionsAttribute : BsonSerializationOptionsAttribute
  24. {
  25. // private fields
  26. private DictionaryRepresentation _representation = DictionaryRepresentation.Document;
  27. // constructors
  28. /// <summary>
  29. /// Initializes a new instance of the BsonDictionaryOptionsAttribute class.
  30. /// </summary>
  31. public BsonDictionaryOptionsAttribute()
  32. {
  33. }
  34. /// <summary>
  35. /// Initializes a new instance of the BsonDictionaryOptionsAttribute class.
  36. /// </summary>
  37. /// <param name="representation">The representation to use for the Dictionary.</param>
  38. public BsonDictionaryOptionsAttribute(DictionaryRepresentation representation)
  39. {
  40. _representation = representation;
  41. }
  42. // public properties
  43. /// <summary>
  44. /// Gets or sets the external representation.
  45. /// </summary>
  46. public DictionaryRepresentation Representation
  47. {
  48. get { return _representation; }
  49. set { _representation = value; }
  50. }
  51. // protected methods
  52. /// <summary>
  53. /// Reconfigures the specified serializer by applying this attribute to it.
  54. /// </summary>
  55. /// <param name="serializer">The serializer.</param>
  56. /// <returns>A reconfigured serializer.</returns>
  57. protected override IBsonSerializer Apply(IBsonSerializer serializer)
  58. {
  59. var dictionaryRepresentationConfigurable = serializer as IDictionaryRepresentationConfigurable;
  60. if (dictionaryRepresentationConfigurable != null)
  61. {
  62. return dictionaryRepresentationConfigurable.WithDictionaryRepresentation(_representation);
  63. }
  64. return base.Apply(serializer);
  65. }
  66. }
  67. }