lokanath das
lokanath das

Reputation: 916

Function App unable to fetch connection string

I have below Folder structure

All below are in a single solution:-

  1. API project (All API related Controller,Helper, Extension Methods)
  2. BLL Class library Project(for all business Layer logic)
  3. DAL Class Library Project(Here the EF Core Db context class is there).
  4. Model Class library(where all Model that are used in the API, EF core are added)
  5. Function App Project( Where there a call to Database to do some checks)

Issue:- There is a API from (1), which gives a call to the Function App(5). Hence in order to the Db check & validation I am initiating the Dbcontext().

    using (var _dbcontext = new sampleDbcontext())
       {
         //Code to validate some Db check 
       }

sampleDbcontext is there in the DAL Class Library (3) where EFcore Dbcontext class is there. so default there is a project reference added to the function app project from DAL Project. In the Dbcontext class i have the below code

public class sampleDbcontext : DbContext
    {
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("DefaultConnection", EnvironmentVariableTarget.Process));
                }
            }
    }  

This DefaultConnection is there in the API project (1). i.e. in the appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=sampleDb; Integrated Security=true;"
  }
}

Every time the Function is executing, its throwing error Value cannot be null. (Parameter 'connectionString'). I am really clueless where i am missing what.

I have added the reference of the APi project(1) from the function App(5), still no result. Reference tree as below

  1. Api project --BLL(2) & model class library(4)
  2. BLL Class library --DAL(3) & model class library(4)
  3. DAL Class library -- model class library(4)
  4. Function App Project --BLL Class Library (2)

Starting project is API project (1). Where is the possible issue?

Upvotes: 1

Views: 160

Answers (1)

lokanath das
lokanath das

Reputation: 916

I was missing with the Initiation of the DbContext in the Function App StartUp. While i was creating the SampleDbcontext as below

using (var _dbcontext = new sampleDbcontext())
       {
         //Code to validate some Db check 
       }

sampleDbcontext() was working ok as the Namespace was added but no object instance was getting assigned to it.

Every time the Empty constructor was getting a call, where there was no Db connection string was mentioned. Connection was basically in the override void OnConfiguring(DbContextOptionsBuilder optionsBuilder). It needed the StartUp Service Layer injection from the Function App & as usual DI fixed the issue.

Upvotes: 1

Related Questions