【发布时间】:2021-12-13 14:54:03
【问题描述】:
我是一名 Python 和 JS 开发人员,几周前我开始使用 ASP.NET 进行开发。
我需要在 .Net Core 上实现 webservice SOAP,但是当我尝试使用 Entity 并在同一解决方案上从另一个项目注入上下文时,我遇到了一个奇怪的错误。
这是我的 Startup.cs
using System.ServiceModel;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Models;
using SoapCore;
using SoapWebServices.Services;
namespace SoapWebServices
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSoapCore();
services.TryAddSingleton<IMyTestService, MyTestService>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSoapEndpoint<IMyTestService>("/Test.svc", new SoapEncoderOptions(), SoapSerializer.XmlSerializer);
}
}
}
这是我的服务合同接口
using OtherProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
namespace SoapWebServices.Services
{
[ServiceContract]
public interface IMyTestService
{
[OperationContract]
string TestMethod(string s);
}
}
这是我的课
using OtherProject.Data;
using OtherProject.Models;
using SoapWebServices.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class MyTestService: IMyTestService
{
public string TestMethod(string id)
{
return "If i receive string build is ok! " + id;
}
}
到目前为止一切正常,但如果我尝试更改 OperationContract
using OtherProject.Data;
using OtherProject.Models;
using SoapWebServices.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class MyTestService: IMyTestService
{
private MyContext _context;
public MyTestService(MyContext context)
{
_context = context;
}
public Info GetInfoById(int id)
{
return _context.Info.FirstOrDefault(c => c.Id == id);
}
}
在构建过程中,我在 Program.cs 上收到一个奇怪的错误
System.AggregateException
消息=无法构建某些服务(验证服务描述符“ServiceType:SoapWebServices.Services.MyTestService Lifetime:Singleton ImplementationType:MyTestService”时出错:无法解析“OtherProject.Data”类型的服务。尝试激活“MyTestService”时的 MyContext'。)
问候
【问题讨论】:
-
该错误告诉您不能将作用域对象注入单例,因为该作用域对象将永远存在。你应该考虑注入一个上下文工厂,这样当你在单例服务中需要一个新的上下文时,你可以得到一个新的上下文。
标签: c# asp.net-core wcf service