SHARE
TWEET

Untitled

a guest Feb 17th, 2017 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.IO;
  7.  
  8. namespace MyService.Helpers
  9. {
  10.     /// <summary>
  11.     /// Helps discovering all the abstract BaseDtoEntity derived classes.
  12.     /// Used like this:     [ServiceKnownType("GetKnownTypes", typeof(ServiceKnownTypesDiscovery))]
  13.     /// on service contract interface
  14.     /// </summary>
  15.     class ServiceKnownTypesDiscovery
  16.     {
  17.         private static List<Type> _cachedTypes = null;
  18.  
  19.         /// <summary>
  20.         /// Extracts known entity types from entities library
  21.         /// </summary>
  22.         /// <param name="provider">Passed in by WCF</param>
  23.         /// <returns>List of BaseDtoEntity derived entity types</returns>
  24.         public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
  25.         {
  26.             // lazy init on first demand
  27.             if (_cachedTypes == null)
  28.             {
  29.                 _cachedTypes = new List<Type>();
  30.                 var baseType = typeof(BaseDtoEntity);
  31.  
  32.                 foreach (var asmFile in Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath ??
  33.                     AppDomain.CurrentDomain.BaseDirectory, "*.Entities.dll")) // project specific name of the library where entities are stored
  34.                 {
  35.                     Assembly asm = Assembly.LoadFrom(asmFile);
  36.                    
  37.                     // BaseDtoEntity is abstract, therefore we excluded it
  38.                     _cachedTypes.AddRange(asm.GetTypes().Where(p => p != baseType &&
  39.                                                             baseType.IsAssignableFrom(p)));
  40.                 }
  41.             }
  42.  
  43.             return _cachedTypes;
  44.         }
  45.     }
  46. }
RAW Paste Data
Top