Created
February 17, 2017 15:51
-
-
Save midix/c7ca87a709c2ea89a617c05c2baa6cd4 to your computer and use it in GitHub Desktop.
Dynamic ServiceKnownTypesDiscovery for WCF services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Reflection; | |
using System.IO; | |
namespace MyService.Helpers | |
{ | |
/// <summary> | |
/// Helps discovering all the abstract BaseDtoEntity derived classes. | |
/// Used like this: [ServiceKnownType("GetKnownTypes", typeof(ServiceKnownTypesDiscovery))] | |
/// on service contract interface | |
/// </summary> | |
class ServiceKnownTypesDiscovery | |
{ | |
private static List<Type> _cachedTypes = null; | |
/// <summary> | |
/// Extracts known entity types from entities library | |
/// </summary> | |
/// <param name="provider">Passed in by WCF</param> | |
/// <returns>List of BaseDtoEntity derived entity types</returns> | |
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider) | |
{ | |
// lazy init on first demand | |
if (_cachedTypes == null) | |
{ | |
_cachedTypes = new List<Type>(); | |
var baseType = typeof(BaseDtoEntity); | |
foreach (var asmFile in Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath ?? | |
AppDomain.CurrentDomain.BaseDirectory, "*.Entities.dll")) // project specific name of the library where entities are stored | |
{ | |
Assembly asm = Assembly.LoadFrom(asmFile); | |
// BaseDtoEntity is abstract, therefore we excluded it | |
_cachedTypes.AddRange(asm.GetTypes().Where(p => p != baseType && | |
baseType.IsAssignableFrom(p))); | |
} | |
} | |
return _cachedTypes; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment