你可以覆盖system.serviceModel配置部分吗?

时间:2009-11-17 19:09:36

标签: .net wcf app-config configurationsection

我们正在尝试创建一个“代理”类,该类将使用其配置属性为WCF服务提供服务。

因为我们无法在app.config文件中存储这些属性,所以我正在寻找一种方法来“代理”它并使用自定义configurationSection,它会根据请求提供所有这些数据。为了做到这一点,我需要告诉.NET框架使用我自己的ConfigurationSection加载system.serviceModel,我不确定我能做到。

如果有人可以批准我的假设,或者甚至更好,请告诉我如何使用其他来源进行WCF配置设置,这将有所帮助。

感谢

1 个答案:

答案 0 :(得分:1)

如果您正在寻找在代码中创建和注册wcf服务的方法,请查看下面的代码示例:

下面是一个创建服务主机对象的方法:

public static ServiceHost RegisterService<T>(object service, int port, string serviceName)
{
    // Returns a list of ipaddress configuration
    IPHostEntry ips = Dns.GetHostEntry(Dns.GetHostName());

    // Select the first entry. I hope it's this maschines IP
    IPAddress ipAddress = ips.AddressList[0];

    // Create the url that is needed to specify where the service should be started
    string urlService = "net.tcp://" + ipAddress.ToString() + String.Format(":{0}/{1}", port, serviceName);

    // Instruct the ServiceHost that the type that is used is a ServiceLibrary.service1
    ServiceHost host = new ServiceHost(service);
    // define events if needed
    //host.Opening += new EventHandler(HostOpeningEvent);
    //host.Opened += new EventHandler(HostOpenedEvent);
    //host.Closing += new EventHandler(HostClosingEvent);
    //host.Closed += new EventHandler(HostClosedEvent);

    // The binding is where we can choose what transport layer we want to use. HTTP, TCP ect.
    NetTcpBinding tcpBinding = new NetTcpBinding();
    tcpBinding.TransactionFlow = false;
    tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
    tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
    tcpBinding.Security.Mode = SecurityMode.None; 

    // Add a endpoint
    host.AddServiceEndpoint(typeof(T), tcpBinding, urlService);

    // A channel to describe the service. Used with the proxy scvutil.exe tool
    ServiceMetadataBehavior metadataBehavior;
    metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
    if (metadataBehavior == null)
    {
        string httpURL = "http://" + ipAddress.ToString() + String.Format(":{0}/{1}", port + 1, serviceName);

        // This is how I create the proxy object that is generated via the svcutil.exe tool
        metadataBehavior = new ServiceMetadataBehavior();
        metadataBehavior.HttpGetUrl = new Uri(httpURL);
        metadataBehavior.HttpGetEnabled = true;
        metadataBehavior.ToString();
        host.Description.Behaviors.Add(metadataBehavior);
    }
    return host;
}

这是你如何使用它:

ServiceHost host = RegisterService<your_service_interface>(your_service, port, "yout_service_name");
host.Open();

希望这有帮助,尊重