internal class Program { private static bool IsInterFaceDll(FileInfo file) { Assembly ass = Assembly.LoadFile(file.FullName); Type[] types = ass.GetTypes(); Type sContractType = typeof(ServiceContractAttribute); foreach (Type type in types) { if (type.IsInterface) { Object[] aa = type.GetCustomAttributes(false); foreach (Object a in aa) { if (a.ToString() == sContractType.ToString()) { return true; } } } } return false; } private static List<Type> GetInterFaceTypes(FileInfo file) { List<Type> result = new List<Type>(); Assembly ass = Assembly.LoadFile(file.FullName); Type[] types = ass.GetTypes(); Type sContractType = typeof(ServiceContractAttribute); foreach (Type type in types) { if (type.IsInterface) { Object[] aa = type.GetCustomAttributes(false); foreach (Object a in aa) { if (a.ToString() == sContractType.ToString()) { result.Add(type); } } } } return result; } private static void Main(string[] args) { try { DirectoryInfo directory = new DirectoryInfo(Environment.CurrentDirectory); FileInfo[] files = directory.GetFiles(); List<FileInfo> list = new List<FileInfo>(); foreach (FileInfo file in files) { if (file.Extension.ToLower() == ".dll") { if (IsInterFaceDll(file)) { list.Add(file); } } } string IP= ConfigurationManager.AppSettings["IP"]; Uri baseHttpAddress = new Uri(string.Format("http://{0}/Bll/", IP)); Uri baseTcpAddress = new Uri(string.Format("net.tcp://{0}/Bll/", IP)); string impAssemblyName = string.Empty; string strClassType = string.Empty; Type classType = null; ServiceHost host = null; Binding wsBinding = null; Binding tcpBinding = null; List<Type> interFaceList=new List<Type>(); ServiceMetadataBehavior metadataBehavior = null; for (int i = 0; i < list.Count; i++) { impAssemblyName = list[i].ToString().Replace(".Contract", ""); interFaceList = GetInterFaceTypes(list[i]); foreach (Type myType in interFaceList) { strClassType = myType.ToString().Replace(".Contract.I", "."); classType =Assembly.LoadFrom(impAssemblyName).GetType(strClassType); host = new ServiceHost(classType, new Uri[] { baseHttpAddress, baseTcpAddress }); wsBinding = new WSHttpBinding(); tcpBinding = new NetTcpBinding(); host.AddServiceEndpoint(myType, wsBinding, ""); host.AddServiceEndpoint(myType, tcpBinding, "tcp"); metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new ServiceMetadataBehavior(); metadataBehavior.HttpGetEnabled = true; host.Description.Behaviors.Add(metadataBehavior); } host.Open(); Console.WriteLine("契约接口:{0};", myType); Console.WriteLine(" 实现类:{0}", classType); Console.WriteLine("Host start..."); Console.WriteLine(); } } Console.ReadLine(); } catch (Exception ex) { Console.Write(ex.Message); Console.ReadLine(); } } }