DiscriminatedInterfaceSerializationProvider.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 System.Reflection;
  17. using MongoDB.Bson.Serialization.Serializers;
  18. namespace MongoDB.Bson.Serialization
  19. {
  20. /// <summary>
  21. /// Provides a serializer for interfaces.
  22. /// </summary>
  23. public class DiscriminatedInterfaceSerializationProvider : BsonSerializationProviderBase
  24. {
  25. /// <inheritdoc/>
  26. public override IBsonSerializer GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
  27. {
  28. if (type == null)
  29. {
  30. throw new ArgumentNullException("type");
  31. }
  32. var typeInfo = type.GetTypeInfo();
  33. if (typeInfo.IsGenericType && typeInfo.ContainsGenericParameters)
  34. {
  35. var message = string.Format("Generic type {0} has unassigned type parameters.", BsonUtils.GetFriendlyTypeName(type));
  36. throw new ArgumentException(message, "type");
  37. }
  38. if (typeInfo.IsInterface)
  39. {
  40. var serializerTypeDefinition = typeof(DiscriminatedInterfaceSerializer<>);
  41. return CreateGenericSerializer(serializerTypeDefinition, new[] { type }, serializerRegistry);
  42. }
  43. return null;
  44. }
  45. }
  46. }