Asp .net Core使用服务实例在Startup.cs中运行的另一个方法中调用方法

时间:2018-06-08 09:00:53

标签: c# asp.net asp.net-core

我的方法是类,它是事件,它获取我需要存储到数据库的数据。

public class DataParser
{
SmsService smsService = new SmsService(..require context...);

 public void ReceiveSms()
 {
     //ParserLogic
     smsService.SaveMessage(...Values...);
 }
}

当服务在上下文的帮助下保存数据时,我需要传递它并在构造函数中初始化。在我创建解析器对象以在Startup上运行之后,我需要在那里传递上下文。

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();
    }
}

那么如何才能正确地将数据保存到db?

1 个答案:

答案 0 :(得分:3)

您需要重构代码。

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

的配置方法中解决所需的问题
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();
}

或者您可以在控制器,服务中随时随地解析解析器。