如何通过Startup.cs中调用的方法在Asp .net核心中保存数据?

时间:2018-06-05 05:33:32

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

我有在 Startup.cs 中调用的方法,在该方法中有一个事件,在事件触发后它必须将数据保存到我的数据库,如下面的代码

public  void SaveRecievedSmsToDb(string phoneNumber, string messageBody, 
    DateTime messageDateTime, string state)
{
    ContactService contactService = new ContactService(_context, _httpContextAccessor);
    MessageService messageService = new MessageService(_context, _httpContextAccessor);

    var contact = contactService.GetContactByNr(phoneNumber);
    var currentUserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    var newMessage = new Message();
    {
        newMessage.UserId = currentUserId;
        newMessage.ContactId = contact.ContactId;
        newMessage.Body = messageBody;
        newMessage.Date = messageDateTime;
        newMessage.isDelivered = true;
        newMessage.State = state;
        messageService.AddMessage(newMessage);
    }


问题是这种方式需要使用 DbContext HttpContextAccessor 的服务,最后我需要将它们写入 Startup.cs 作为注入isn& #39;工作和投掷InvalidOperationException: Unable to resolve service for type 'SmsSender.Data.ApplicationDbContext' while attempting to activate 'SmsSender.Startup'.
从事件中保存数据的最佳方法是什么?


    public class Startup
{
    private IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        AtSmsReceiver _atSmsReceiver = new AtSmsReceiver();//If I'm trying to use Http and AppDb contexts it asking to pass them here

        //Opens port for runtime
        COMPortSettings.OpenPort();
        //Runtime sms receiver
        _atSmsReceiver.ReceiveSms();

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlite(_configuration.GetConnectionString("SmsSender")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddScoped<IContactService, ContactService>();
        services.AddScoped<IMessageService, MessageService>();
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddTransient<IMacroService, MacroService>();
        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvc();
    }
 //All other logic...
}

0 个答案:

没有答案