这个问题及其答案已经有将近一年的历史了。尽管如此,我也面临同样的问题。
简短的答案是您已经发现的。它不起作用。然而这并没有阻止我们。后来的一些研究和对激活机制的一点“潜水”提供了以下工作解决方案:
public class CustomRouting
{
public static void Route(string routePrefix, ServiceHostFactoryBase serviceHostFactory, Type serviceType)
{
var serviceHostingEnvironment = new StaticReflectionWrapper(typeof (ServiceHostingEnvironment));
serviceHostingEnvironment.StaticMethod("EnsureInitialized");
var hostManager = serviceHostingEnvironment.GetStaticField("hostingManager");
var hostingManager = new InstanceReflectionWrapper(hostManager);
var normalizedAddress = hostingManager.Method<string>("NormalizedRelativeAddress", routePrefix);
var serviceActivation = new KeyValuePair<string, string>(normalizedAddress, string.Format("{0}|{1}|{2}", normalizedAddress, serviceHostFactory.GetType().FullName, serviceType.FullName));
hostingManager.GetField<Hashtable>("serviceActivations").Add(serviceActivation.Key, serviceActivation.Value);
var tD = StaticReflectionWrapper.Resolve(typeof (ServiceHostingEnvironment).Assembly, "TD");
if (tD.StaticMethod<bool>("CBAEntryReadIsEnabled"))
{
tD.StaticMethod("CBAEntryRead", routePrefix, serviceActivation.Key);
}
ServiceHostingEnvironment.EnsureServiceAvailable(serviceActivation.Key);
}
}
帮助类 StaticReflectionWrapper 和 InstanceReflectionWrapper 只是帮助类保持反射的可读性。
您使用 Route 方法如下:
var fact = new CustomServiceHostFactory();
CustomRouting.Route("DynamicServices/" + service.GetType().Name + ".svc", fact, service.GetType());
服务变量是 ServiceContract 的实现。
使用这个需要自担风险,因为这真的会进入我们不应该来的地区。尽管如此,它仍然有效。
希望这可以减少很多人的搜索时间并打开封闭的大门。