其实现实的方式很简单,就是在启动时,根据接口与 实现类的对应关系进行自动注册。
话不多说,内容如下。有用就拿走吧
#region 获取类里相关的所有的类型
List<Assembly> usedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select((item) => Assembly.Load(item)).ToList();
List<Type> list = new List<Type>();
foreach (Assembly assembly in usedAssemblies)
{
list.AddRange(assembly.GetTypes());
}
foreach (Type interfaceType in (from item in list where item.GetCustomAttributes(typeof(ServiceContractAttribute), true).Length != 0 select item).ToList())
{
if (interfaceType.FullName.ToLower().StartsWith("system.") == true)
{
continue;
}
Type serviceType = (from item in list where item.GetInterface(interfaceType.FullName) != null select item).FirstOrDefault();
if (serviceType != null)
{
BasicHttpBinding tcpBinding = new BasicHttpBinding();
tcpBinding.CloseTimeout = tcpBinding.OpenTimeout = new TimeSpan(0, 1, 0);
tcpBinding.ReceiveTimeout = tcpBinding.SendTimeout = new TimeSpan(0, 10, 0);
tcpBinding.TransferMode = TransferMode.Buffered;
tcpBinding.MaxBufferPoolSize = long.MaxValue;
tcpBinding.MaxBufferSize = int.MaxValue;
tcpBinding.MaxReceivedMessageSize = int.MaxValue;
tcpBinding.MaxBufferSize = int.MaxValue;
tcpBinding.Security = new BasicHttpSecurity() { Mode = BasicHttpSecurityMode.None };
string url = "http://127.0.0.1:10679/LogOnService.svc".Replace("LogOnService", serviceType.Name);
Console.WriteLine(string.Format("准备打开{0}-{1}:地址{2}", interfaceType.FullName, serviceType.FullName, url));
ServiceHost host = new ServiceHost(serviceType);
host.AddServiceEndpoint(interfaceType, tcpBinding, url);
host.Opened += delegate
{
Console.WriteLine(string.Format("打开成功:{0}-{1}:地址{2}", interfaceType.FullName, serviceType.FullName, url));
};
host.Open();
//host.Close();
}
}
#endregion