我有一个带有事件方法的类,它获取我需要存储到数据库的数据。
public class DataParser
{
SmsService smsService = new SmsService(..require context...);
public void ReceiveSms()
{
//ParserLogic
smsService.SaveMessage(...Values...);
}
}
由于服务在上下文的帮助下保存数据,我需要传递它并在构造函数中初始化。在我创建要在 Startup 上运行的解析器对象时执行此操作后,ir 需要在那里传递上下文。
public class Startup
{
DataParser data = new DataParser(...requires db context...)
public void ConfigureServices(IServiceCollection services)
{
//Opens port for runtime
InnerComPortSettings.OpenPort();
//Runtime sms receiver
data.ReceiveSms();
}
}
那么如何正确的将数据保存到数据库呢?
最佳答案
您需要重构您的代码。
1) 您不必在解析器中创建服务。将其作为依赖项传递
public class DataParser
{
public DataParser(SmsService smsService)
{
SmsService _smsService = smsService;
}
public void ReceiveSms( )
{
//ParserLogic
smsService.SaveMessage(...Values...);
}
}
2) 现在你需要注册你的上下文、解析器和服务
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options =>... your options here); // register your context
services.AddSingleton<SmsService, SmsService>(); // register your sms servcice which is required data context
services.AddSingleton<DataParser, DataParser>(); // register your parser
}
5) 现在是时候重构您的短信服务了
public class SmsService
{
private readonly IServiceScopeFactory _scopeFactory;
public SmsService(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public async Task SaveMessage(....)
{
using (var scope = _scopeFactory.CreateScope())
{
using (var ctx = scope.ServiceProvider.GetService<MyDbContext>())
{
... make changes
await ctx.SaveChangesAsync();
}
}
}
}
4) 当一切都注册好后,你可以在Startup
类的configure方法中解决你需要的东西
public void Configure(IApplicationBuilder app, DataParser data) // resolving your data perser and using it
{
//Opens port for runtime
InnerComPortSettings.OpenPort();
//Runtime sms receiver
data.ReceiveSms();
}
或者您可以在 Controller 、服务以及任何您想要的地方解析您的解析器。
关于c# - Asp .net Core 使用服务实例调用在 Startup.cs 中运行的另一个方法中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50756984/