AttributedSerializationProvider.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* Copyright 2010-2016 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 System.Linq;
  17. using System.Reflection;
  18. using MongoDB.Bson.Serialization.Attributes;
  19. namespace MongoDB.Bson.Serialization
  20. {
  21. /// <summary>
  22. /// Provides serializers based on an attribute.
  23. /// </summary>
  24. public class AttributedSerializationProvider : BsonSerializationProviderBase
  25. {
  26. /// <inheritdoc/>
  27. public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
  28. {
  29. if (type == null)
  30. {
  31. throw new ArgumentNullException("type");
  32. }
  33. var typeInfo = type.GetTypeInfo();
  34. if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
  35. {
  36. var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type));
  37. throw new ArgumentException(message, "type");
  38. }
  39. var serializerAttributes = typeInfo.GetCustomAttributes<BsonSerializerAttribute>(false).ToArray();
  40. if (serializerAttributes.Length == 1)
  41. {
  42. var serializerAttribute = (BsonSerializerAttribute)serializerAttributes[0];
  43. return serializerAttribute.CreateSerializer(type);
  44. }
  45. return null;
  46. }
  47. }
  48. }