Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在selfhost环境中注入对用作RESTFul服务的WCF服务的依赖关系_C#_Wcf_Dependency Injection_Simple Injector - Fatal编程技术网

C# 如何在selfhost环境中注入对用作RESTFul服务的WCF服务的依赖关系

C# 如何在selfhost环境中注入对用作RESTFul服务的WCF服务的依赖关系,c#,wcf,dependency-injection,simple-injector,C#,Wcf,Dependency Injection,Simple Injector,我需要一些示例,说明如何在自宿主环境中使用WCF技术并通过使用DI容器(可能是SimpleInjector)实现RESTfull服务 在上,我发现了如何集成定制工厂,但它是为ServiceHost设计的,但这不适合使用WebServiceHost的RESTFull服务 我试图将服务主机配置为与webHttpBinding兼容,但未发生任何问题,我收到此类错误: <Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelop

我需要一些示例,说明如何在自宿主环境中使用WCF技术并通过使用DI容器(可能是SimpleInjector)实现RESTfull服务

在上,我发现了如何集成定制工厂,但它是为ServiceHost设计的,但这不适合使用WebServiceHost的RESTFull服务

我试图将服务主机配置为与webHttpBinding兼容,但未发生任何问题,我收到此类错误:

<Fault
    xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none">
    <Code>
        <Value>Sender</Value>
        <Subcode>
            <Value
                xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">a:DestinationUnreachable
            </Value>
        </Subcode>
    </Code>
    <Reason>
        <Text xml:lang="it-IT">Impossibile elaborare nel destinatario il messaggio con To 'http://localhost:8733/3AdispPushBatchService/pushpost' a causa di una mancata corrispondenza AddressFilter in EndpointDispatcher. Controllare la corrispondenza di EndpointAddresses del mittente e del destinatario.</Text>
    </Reason>
</Fault>
IAaaDispPushBatchService.cs

using System;
using System.Configuration;
using System.IO;
using System.ServiceModel.Activation;
using System.Text;
using Newtonsoft.Json;
namespace AAARestService
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AAADispPushBatchService : IAaaDispPushBatchService
    {
        public string GetBatchJson(Stream jsonFileContent)
        {
            try
            {
                var sr = new StreamReader(jsonFileContent, Encoding.UTF8);
                var str = sr.ReadToEnd();


                if (String.IsNullOrWhiteSpace(str))
                    throw new ArgumentException("No data inside body request");
                var definition = new { BatchName = "" };
                var json = JsonConvert.DeserializeAnonymousType(str, definition);
                if (json == null)
                    throw new ArgumentException("No valid json inside");
                if (String.IsNullOrWhiteSpace(json.BatchName))
                    throw new ArgumentException("BatchName not present");

                var currentDir = ConfigurationManager.AppSettings["BatchPath"];
                Directory.CreateDirectory(currentDir);

                var filepath = Path.Combine(currentDir, json.BatchName+".json");

                File.WriteAllText(filepath, str);

                return $"Saved in {filepath}";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }
}
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace AAARestService
{  
    [ServiceContract(Name = "AAADispPushBatchService")]
    public interface IAaaDispPushBatchService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "pushpost", BodyStyle = WebMessageBodyStyle.Bare,ResponseFormat = WebMessageFormat.Json)]
        string GetBatchJson(Stream jsonFileContent);
    }
}
编辑!!!!! 顺便说一句,我尝试添加simpleinjector,以下是基于我在博客中发现的示例

Bootstrapper.cs

using System.Reflection;
using SimpleInjector;

namespace AAARestService
{
    public static class BootStrapper
    {
        public static readonly Container Container;

        static BootStrapper()
        {
            Container container = new Container();


            container.Register<IMyDateTimeService,MyDAteTimeService>();

            container.RegisterWcfServices(Assembly.GetExecutingAssembly());

            Container = container;
        }
    }
}
主要

static void Main(字符串[]args)
{
尝试
{
Uri httpUrl=新Uri(“http://localhost:8733/3AdispPushBatchService");
Uri httpUrl1=新Uri(“http://localhost:8734/3AdispPushBatchService");
//ServiceHost selfhost=新的ServiceHost(typeof(aaadispushBatchService),httpUrl);
//ServiceEndpoint sep=selfhost.AddServiceEndpoint(typeof(IAaaDispPushBatchService),新的WebHttpBinding(),httpUrl);
//添加(新的WebHttpBehavior());
//ServiceMetadataBehavior smb=新ServiceMetadataBehavior();
//smb.HttpGetEnabled=true;
//selfhost.Description.Behaviors.Add(smb);
MyWebServiceHostFactory=新的MyWebServiceHostFactory();
var selfhost=factory.GetWebServiceEndpoint(typeof(aaadispushBatchService),httpUrl);
selfhost.Open();
//WebServiceHost webHost=新的WebServiceHost(typeof(aaadispushBatchService),httpUrl1);
//webHost.Open();
foreach(selfhost.Description.Endpoints中的ServiceEndpoint se)
Console.WriteLine(“服务是端点为“+se.Address”的主机);
//foreach(webHost.Description.Endpoints中的ServiceEndpoint se)
//Console.WriteLine(“服务是端点为“+se.Address”的主机);
//Console.WriteLine(“ASP.Net:+ServiceHostingEnvironment.AspNetCompatibilityEnabled”);
Console.WriteLine(“主机正在运行…按键停止”);
Console.ReadLine();
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
Console.ReadLine();
}
}

我还没有尝试使用依赖注入技术与WCF集成,也许该博客中的解决方案值得一试。我也不建议您在WCF中使用依赖项注入,因为它本身不支持依赖项注入。此外,对于
servicehost
hosting
WCF REST-style
服务,我们需要在服务端点上添加
WebHttp
行为。请参考以下代码实现

   Uri uri = new Uri("http://localhost:8004");
            WebHttpBinding binding = new WebHttpBinding();
            binding.Security.Mode = WebHttpSecurityMode.None;

            using (ServiceHost sh = new ServiceHost(typeof(MyService), uri))
            {
                ServiceEndpoint se=sh.AddServiceEndpoint(typeof(IService), binding,"");
                se.EndpointBehaviors.Add(new WebHttpBehavior());

                sh.Opened += delegate
                {
                    Console.WriteLine("Service is ready");
                };
                sh.Closed += delegate
                {
                    Console.WriteLine("Service is clsoed");
                };
    sh.Open();
                Console.ReadLine();
                //pause
                sh.Close();
                Console.ReadLine();

如果有什么我可以帮忙的,请随时告诉我。

我还没有尝试使用依赖注入技术与WCF集成,也许该博客中的解决方案值得一试。我也不建议您在WCF中使用依赖项注入,因为它本身不支持依赖项注入。此外,对于
servicehost
hosting
WCF REST-style
服务,我们需要在服务端点上添加
WebHttp
行为。请参考以下代码实现

   Uri uri = new Uri("http://localhost:8004");
            WebHttpBinding binding = new WebHttpBinding();
            binding.Security.Mode = WebHttpSecurityMode.None;

            using (ServiceHost sh = new ServiceHost(typeof(MyService), uri))
            {
                ServiceEndpoint se=sh.AddServiceEndpoint(typeof(IService), binding,"");
                se.EndpointBehaviors.Add(new WebHttpBehavior());

                sh.Opened += delegate
                {
                    Console.WriteLine("Service is ready");
                };
                sh.Closed += delegate
                {
                    Console.WriteLine("Service is clsoed");
                };
    sh.Open();
                Console.ReadLine();
                //pause
                sh.Close();
                Console.ReadLine();

如果有什么我可以帮忙的,请随时告诉我。

为什么不使用WebApi?对于REST服务,WebApi比WCF好。因为我的项目是一个桌面应用程序,需要集成一些WCF服务,我以前在其他项目自托管WCF服务中使用过。我现在看到WebApi可以自托管,所以我尝试一下为什么不使用WebApi?对于REST服务,WebApi比WCF好。因为我的项目是一个桌面应用程序,需要集成一些WCF服务,我以前在其他项目自托管WCF服务中使用过。我现在看到WebApi可以自托管,所以我给它一个tryThanks@Abraham Qian,现在服务主机使用http绑定谢谢@Abraham Qian,现在服务主机使用http绑定
   Uri uri = new Uri("http://localhost:8004");
            WebHttpBinding binding = new WebHttpBinding();
            binding.Security.Mode = WebHttpSecurityMode.None;

            using (ServiceHost sh = new ServiceHost(typeof(MyService), uri))
            {
                ServiceEndpoint se=sh.AddServiceEndpoint(typeof(IService), binding,"");
                se.EndpointBehaviors.Add(new WebHttpBehavior());

                sh.Opened += delegate
                {
                    Console.WriteLine("Service is ready");
                };
                sh.Closed += delegate
                {
                    Console.WriteLine("Service is clsoed");
                };
    sh.Open();
                Console.ReadLine();
                //pause
                sh.Close();
                Console.ReadLine();