Dan*_*imo 4 c# asp.net asp.net-core
我有一个带有方法的类,它是事件,它获取我需要存储到数据库的数据。
public class DataParser
{
SmsService smsService = new SmsService(..require context...);
public void ReceiveSms()
{
//ParserLogic
smsService.SaveMessage(...Values...);
}
}
Run Code Online (Sandbox Code Playgroud)
由于服务在上下文的帮助下保存数据,我需要传递它并在构造函数中初始化。在我这样做之后,当我创建解析器对象以在启动时运行时,需要在那里传递上下文。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
那么如何正确地将数据保存到数据库呢?
你需要重构你的代码。
1)您不必在解析器中创建服务。将其作为依赖项传递
public class DataParser
{
public DataParser(SmsService smsService)
{
SmsService _smsService = smsService;
}
public void ReceiveSms( )
{
//ParserLogic
smsService.SaveMessage(...Values...);
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
4)当一切都注册后,您可以在Startup类的配置方法中解决您需要的问题
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();
}
Run Code Online (Sandbox Code Playgroud)
或者你可以在控制器、服务中解析你的解析器,任何你想要的地方。
| 归档时间: |
|
| 查看次数: |
5152 次 |
| 最近记录: |