首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP.NET核心6后台服务实体框架注入

ASP.NET核心6后台服务实体框架注入
EN

Stack Overflow用户
提问于 2022-06-23 22:22:40
回答 1查看 746关注 0票数 0

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

我希望在后台服务中使用实体框架,但是EF变量(IAppRepository)为null。我得到了一个错误:

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

如何注入DbContext

我的代码:

Program.cs

代码语言:javascript
复制
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 (我的后台服务)

代码语言:javascript
复制
    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

代码语言:javascript
复制
public interface IAppRepository
{
        void Add<T>(T entity);
        bool SaveAll();
}

AppRepository.cs

代码语言:javascript
复制
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;
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-23 22:34:21

将构造函数更改为只使用一个而不是两个

代码语言:javascript
复制
public class APIService : BackgroundService
{
    private readonly ILogger<APIService> _logger;
    private readonly IAppRepository _appRepository;

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

在您的代码中,第一个构造函数将通过依赖项注入来解析,因此异常消息是正确的,您的_appRepositorynull

您还可以找到更多/其他详细信息here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72737177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档