Daniel Žeimo
Daniel Žeimo

Reputation: 163

Asp .net Core using service instance to call method in another method which runs in Startup.cs

I have class with method which is event and its gets data which i need to store to database.

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

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

As service saves data with help of context I need to pass it and initialize in constructor. After i do that when I'm creating my parser object to run on Startup ir requires to pass context there.

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

So how can I properly save data to db?

Upvotes: 5

Views: 10719

Answers (1)

tym32167
tym32167

Reputation: 4891

you need to refactor your code.

1) You dont have to create service inside parser. Pass it as dependency

public class DataParser
{   
    public DataParser(SmsService smsService)
    {
        SmsService _smsService = smsService;
    }

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

2) Now you need to register your context and parser and service

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) now its time to refactor your sms service

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) When everything registered, you can resolve what you need in configure method of Startup class

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

Or you can resolve your parser in controllers, services, everuwhere you want.

Upvotes: 8

Related Questions