ASP.NET Core 6背景服务实体框架注入

发布于 2025-02-10 05:49:26 字数 3983 浏览 2 评论 0原文

我正在使用.NET 6和实体框架。

我想在我的背景服务中使用实体框架,但是我的EF变量(iapprepository)为空。我得到了这个错误:

system.nullReferenceException:“对象引用未设置为对象的实例。”

如何注入dbContext

我的代码:

program.cs

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<APIService>();
    })
    .Build();
await host.RunAsync();

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DataContext>(x=>
x.UseSqlServer(builder.Configuration.GetConnectionString("BankSearchConnection")));
builder.Services.AddScoped<IAppRepository, AppRepository>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html"); ;
app.Run();

apiservice.cs (我的背景服务)

    public class APIService : BackgroundService
    {
        private readonly ILogger<APIService> _logger;

        public APIService(ILogger<APIService> logger)
        {
            _logger = logger;
        }

        private IAppRepository _appRepository;

        public APIService(IAppRepository appRepository)
        {
            _appRepository = appRepository;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Banka verileri güncellendi! Saat: {time}", DateTimeOffset.Now);

                BankAPI();
                _logger.LogInformation("Garanti Bankası geçti");
                await Task.Delay(180000, stoppingToken);
            }
        }

        private void BankAPI()
        {
            string uri = "https://apis.garantibbva.com.tr:443/loans/v1/paymentPlan";
            var client = new RestClient(uri);
            var request = new RestRequest(Method.POST);
            request.AddHeader("apikey", "l7xx8af86c14ea7e44e0ab3fbfcc6137ae09");
            request.AddQueryParameter("loanType", "1");
            request.AddQueryParameter("campaignCode", "BankSearch");
            request.AddQueryParameter("loanAmount", "10000");
            IRestResponse response = client.Execute(request);
            
            int dueNum = 3;
            float monthlyAnnualCostRate = JObject.Parse(response.Content)["data"]["list"]
                .Where(p => (int)p["dueNum"] == dueNum)
                .Select(p => (float)p["monthlyAnnualCostRate"])
                .FirstOrDefault();

            _logger.LogInformation("Garanti Bankası Response: {monthlyAnnualCostRate}", monthlyAnnualCostRate);

            AddKredi("Garanti Bankası",1,monthlyAnnualCostRate);
        }

        private void AddKredi(string bankaAdi, int krediVadeKodu, float krediFaizi)
        {
            Kredi kredi = new Kredi(bankaAdi, krediVadeKodu, krediFaizi);
            _appRepository.Add(kredi); //I take _apprepository=null error in this line
            _appRepository.SaveAll();
        }
    }

iapprepository.cs

public interface IAppRepository
{
        void Add<T>(T entity);
        bool SaveAll();
}

apprepository.cs

public class AppRepository : IAppRepository
{
        private DataContext _context;

        public AppRepository(DataContext context)
        {
            _context = context;
        }

        public void Add<T>(T entity)
        {
            _context.Add(entity);
        }

        public bool SaveAll()
        {
            return _context.SaveChanges() > 0;
        }
    }

I'm using .NET 6 and Entity Framework.

I want use Entity Framework in my background service, but my EF variable (IAppRepository) is null. And I get this error:

System.NullReferenceException:'Object reference not set to an instance of an object.'

How can I inject the DbContext?

My code:

Program.cs

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<APIService>();
    })
    .Build();
await host.RunAsync();

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DataContext>(x=>
x.UseSqlServer(builder.Configuration.GetConnectionString("BankSearchConnection")));
builder.Services.AddScoped<IAppRepository, AppRepository>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html"); ;
app.Run();

APIService.cs (my background service)

    public class APIService : BackgroundService
    {
        private readonly ILogger<APIService> _logger;

        public APIService(ILogger<APIService> logger)
        {
            _logger = logger;
        }

        private IAppRepository _appRepository;

        public APIService(IAppRepository appRepository)
        {
            _appRepository = appRepository;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Banka verileri güncellendi! Saat: {time}", DateTimeOffset.Now);

                BankAPI();
                _logger.LogInformation("Garanti Bankası geçti");
                await Task.Delay(180000, stoppingToken);
            }
        }

        private void BankAPI()
        {
            string uri = "https://apis.garantibbva.com.tr:443/loans/v1/paymentPlan";
            var client = new RestClient(uri);
            var request = new RestRequest(Method.POST);
            request.AddHeader("apikey", "l7xx8af86c14ea7e44e0ab3fbfcc6137ae09");
            request.AddQueryParameter("loanType", "1");
            request.AddQueryParameter("campaignCode", "BankSearch");
            request.AddQueryParameter("loanAmount", "10000");
            IRestResponse response = client.Execute(request);
            
            int dueNum = 3;
            float monthlyAnnualCostRate = JObject.Parse(response.Content)["data"]["list"]
                .Where(p => (int)p["dueNum"] == dueNum)
                .Select(p => (float)p["monthlyAnnualCostRate"])
                .FirstOrDefault();

            _logger.LogInformation("Garanti Bankası Response: {monthlyAnnualCostRate}", monthlyAnnualCostRate);

            AddKredi("Garanti Bankası",1,monthlyAnnualCostRate);
        }

        private void AddKredi(string bankaAdi, int krediVadeKodu, float krediFaizi)
        {
            Kredi kredi = new Kredi(bankaAdi, krediVadeKodu, krediFaizi);
            _appRepository.Add(kredi); //I take _apprepository=null error in this line
            _appRepository.SaveAll();
        }
    }

IAppRepository.cs

public interface IAppRepository
{
        void Add<T>(T entity);
        bool SaveAll();
}

AppRepository.cs

public class AppRepository : IAppRepository
{
        private DataContext _context;

        public AppRepository(DataContext context)
        {
            _context = context;
        }

        public void Add<T>(T entity)
        {
            _context.Add(entity);
        }

        public bool SaveAll()
        {
            return _context.SaveChanges() > 0;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无风消散 2025-02-17 05:49:26

更改您的构造函数以仅使用一个代码中的一个而不是两个,

public class APIService : BackgroundService
{
    private readonly ILogger<APIService> _logger;
    private readonly IAppRepository _appRepository;

    public APIService(IAppRepository appRepository, ILogger<APIService> logger)
    {
        _appRepository = appRepository;
        _logger = logger;
    }
}

第一个构造函数将通过依赖项注入来解决,因此异常消息是正确的,您的_appRepository is null

您还可以找到更多/其他详细信息在这里

Change your constructor to use only one instead of two

public class APIService : BackgroundService
{
    private readonly ILogger<APIService> _logger;
    private readonly IAppRepository _appRepository;

    public APIService(IAppRepository appRepository, ILogger<APIService> logger)
    {
        _appRepository = appRepository;
        _logger = logger;
    }
}

In your code the first constructor will be resolved by Dependency Injection so the exception message is correct your _appRepository is null.

You can also find more/other details here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文