【发布时间】:2015-12-14 12:02:24
【问题描述】:
我在 wcf 服务中工作,其中服务动态托管在随机端口上。动态加载服务契约和服务行为程序集,并扫描所有类型以匹配服务名称及其版本。 相同的服务可以在不同的版本上运行。为了区分服务的版本,我们创建了一个自定义的 ServiceIdentifierAttribute 属性。
public class ServiceIdentifierAttribute : Attribute
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _version;
public string Version
{
get { return _version; }
set { _version = value; }
}
}
服务契约及其行为类用 SerivceIdentifierAttribute 修饰。
[ServiceContract(Name = "ABCServicesV0.0.0.0")]
[ServiceIdentifierAttribute(Name = "ABCServicesV0.0.0.0", Version = "V0.0.0.0")]
public interface IABCService
{
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, Name = "ABCServicesV0.0.0.0")]
public class ABCService : IABCService
{}
服务合同,属性在一个程序集中定义,而服务实现在另一个程序集中。我们有一个 GenericSericeHost 控制台应用程序,它通过加载两个程序集来动态托管服务。我们需要搜索所有类型并从程序集中获取服务合同类型。
private static bool SeachForServiceContractAttribute(Type type, String serviceIdentifier)
{
if (type.IsDefined(typeof(ServiceContractAttribute), false))
{
var attributeTypes = type.GetCustomAttributes();
foreach (var attributeType in attributeTypes)
{
try
{
ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType;
if (attribute != null && !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Equals(serviceIdentifier))
return true;
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}
return false;
}
GenericServiceHost 具有对 ServiceContract 程序集的引用。在运行时
ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType;
正在抛出错误无效的强制转换异常。由于 ServiceContractAttribute 的两个版本在运行时加载。一个是动态加载的,另一个是通过 GenerciServiceHost 引用加载的。我们无法删除服务引用,因为它会导致 ServiceContractAttribute not defined complication 错误。
所有不同的服务实现都会有不同的程序集,我们不想从genereicservicehost 添加对所有程序集的引用,因为当任何服务行为发生变化时,它会导致重建genericservicehost。我们希望 GenericServiceHost 一直运行。
我们如何通过从程序集加载类型转换为程序集加载类型来使其工作
ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType;
任何指针?
【问题讨论】:
-
为什么要加载两次?属性是一种基础结构事物,应该简单地引用该程序集。是否动态加载其他内容应该不会影响该程序集。
标签: c# .net wcf reflection .net-assembly