Служба WCF хоста без файла конфигурации

1

Я хочу разместить службу WCF, но я не хочу использовать файл app.config но что-то похожее на это:

// 2nd Procedure:
// Use the binding in a service
// Create the Type instances for later use and the URI for 
// the base address.
Type contractType = typeof(ICalculator);
Type serviceType = typeof(Calculator);
Uri baseAddress = new Uri("http://localhost:8036/SecuritySamples/");

// Create the ServiceHost and add an endpoint, then start
// the service.
ServiceHost myServiceHost = new ServiceHost(serviceType, baseAddress);
myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator");

//enable metadata
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
myServiceHost.Description.Behaviors.Add(smb);

myServiceHost.Open();

После этого я хочу добавить проект службы Windows и разместить мой сервис.

Какой проект использовать? Я не хочу консоли или winforms, я хочу только службу Windows

Я проверил Windows Service project и у меня есть это:

static void Main()
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
        new Service1() 
    };
    ServiceBase.Run(ServicesToRun);
}

Где я должен поставить служебный код?

  • 0
    Я должен был проверить, но я почти уверен, что в Visual Studio есть шаблон проекта Windows Service. Используйте это.
  • 0
    Пожалуйста, смотрите мое обновление
Теги:
wcf

2 ответа

0
Лучший ответ

Вы бы поместили код из своего первого блока кода в функцию OnStart Service1.

private _myServiceHost;

protected override void OnStart(string[] args)
{
    if(_myServiceHost != null)
    {
        //Close the connection if the service was already opened.
        _myServiceHost.Close();
    }

    // 2nd Procedure:
    // Use the binding in a service
    // Create the Type instances for later use and the URI for 
    // the base address.
    Type contractType = typeof(ICalculator);
    Type serviceType = typeof(Calculator);
    Uri baseAddress = new Uri("http://localhost:8036/SecuritySamples/");

    // Create the ServiceHost and add an endpoint, then start
    // the service.
    _myServiceHost = new ServiceHost(serviceType, baseAddress);
    _myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator");

    //enable metadata
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    _myServiceHost.Description.Behaviors.Add(smb);

    _myServiceHost.Open();
}

//Adding a close on OnStop gives you a more graceful shutdown of your service, letting clients finish the work they are currently on
protected override void OnStop()
{
    if(_myServiceHost != null)
    {
        _myServiceHost.Close();
        _myServiceHost = null;
    }
}
0

ниже вы можете найти рабочий пример:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, IncludeExceptionDetailInFaults = true)]
    public class SMTX_Service : ISMTX_Service
    {
    }
 private void StartService(Uri baseUri, string EndPointName, bool EnableServiceDiscovery)
        {
                var serviceUri = new Uri(baseUri, EndPointName);
                Host = new ServiceHost(typeof(WCF_TEST.SMTX_Service), baseUri);
                Host.Faulted += h_ServiceFaulted;
                Host.Opened += h_ServiceOpened;
                Host.Closed += h_ServiceClosed;
                WSHttpBinding wsHttpBinding = new WSHttpBinding();
                wsHttpBinding.Security.Mode = SecurityMode.Message;
                wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.TripleDesSha256Rsa15;
                wsHttpBinding.Security.Message.EstablishSecurityContext = true;
                wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
                wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
                wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
                wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                wsHttpBinding.Security.Transport.Realm = "";
                wsHttpBinding.MaxBufferPoolSize = 524288;
                wsHttpBinding.MaxReceivedMessageSize = 4194304;
                ServiceEndpoint SEP = Host.AddServiceEndpoint(typeof(WCF_TEST.ISMTX_Service), wsHttpBinding, EndPointName);
                SEP.Name = EndPointName;
                SEP.Address = new EndpointAddress(serviceUri);
                SEP.Binding = wsHttpBinding;
                ServiceMetadataBehavior SMB = new ServiceMetadataBehavior();
                SMB.HttpGetEnabled = EnableServiceDiscovery;
                Host.Description.Behaviors.Add(SMB);
                ServiceCredentials SC = new ServiceCredentials();
                SC.ServiceCertificate.Certificate = GetCertificate();
                SC.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                SC.UseIdentityConfiguration = false;
                SC.ClientCertificate.Certificate = GetCertificate();
                SC.WindowsAuthentication.AllowAnonymousLogons = false;
                SC.WindowsAuthentication.IncludeWindowsGroups = true;
                SC.Peer.PeerAuthentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                Host.Description.Behaviors.Add(SC);
                Host.Open();
        }

в приведенном выше примере используются сертификаты из хранилища сертификатов для аутентификации. функция GetCertificate не включена. при необходимости измените алгоритм сообщения и согласования. вы можете запустить службу следующим образом:

StartService(new Uri("..."), "WCF_NAME", true);
  • 0
    Я думаю, что вопрос больше в том, что он не знает, куда поместить StartService(... вызов, а не то, что положить в этот вызов.
  • 0
    да, вы правы @ ScottChamberlain я не обращал внимания. но полный код может быть полезен для кого-то :)
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню