BsonClassMapSerializationProvider.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.Reflection;
  17. namespace MongoDB.Bson.Serialization
  18. {
  19. /// <summary>
  20. /// Represents the class map serialization provider.
  21. /// </summary>
  22. internal class BsonClassMapSerializationProvider : BsonSerializationProviderBase
  23. {
  24. /// <inheritdoc/>
  25. public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
  26. {
  27. if (type == null)
  28. {
  29. throw new ArgumentNullException("type");
  30. }
  31. var typeInfo = type.GetTypeInfo();
  32. if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
  33. {
  34. var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type));
  35. throw new ArgumentException(message, "type");
  36. }
  37. if ((typeInfo.IsClass || (typeInfo.IsValueType && !typeInfo.IsPrimitive)) &&
  38. !typeof(Array).GetTypeInfo().IsAssignableFrom(type) &&
  39. !typeof(Enum).GetTypeInfo().IsAssignableFrom(type))
  40. {
  41. var classMap = BsonClassMap.LookupClassMap(type);
  42. var classMapSerializerDefinition = typeof(BsonClassMapSerializer<>);
  43. var classMapSerializerType = classMapSerializerDefinition.MakeGenericType(type);
  44. return (IBsonSerializer)Activator.CreateInstance(classMapSerializerType, classMap);
  45. }
  46. return null;
  47. }
  48. }
  49. }