67966749

Date: 2021-06-14 09:07:50
Score: 5.5
Natty:
Report link

Good morning @Martin, this was very handy, thank you. I have added the following to the console app project file:

<!-- Try and nest the appsettings when it's not a web sdk project. -->
  <ItemGroup Condition="'$(IsSdkProject)' == 'true' AND '$(IsWebSdkProject)' == 'false'">
    <Content Include="..\StockTradingSimulator.ApiHost\appsettings.*.json">
      <DependentUpon>appsettings.json</DependentUpon>
    </Content>
    <Content Include="appsettings*.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </Content>
  </ItemGroup>

When running the console app with dotnet run, the Web API appsettings.json file is now found.

I want to send an email from my console app, the email sender is in the web API project and has a dependency on the dbContext.

The Web API class derived from DbContext uses the following to get the connection string:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(_configuration.GetConnectionString("StockTrading"));

appsettings.json contains the connection string to my SQL Server database.

dotnet run for the console app throws an error System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')

Do you know how I can access the connection string in the console app? I tried the following in my console app service collection extension method, to no avail:

internal static IServiceCollection AddStockUpdater(this IServiceCollection services)
        {
            var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json", false)
                    .Build();

            services.AddHttpClient("trading", client => client.BaseAddress = new Uri("http://localhost:4000"));

            services
                .AddSingleton(configuration)
                .Configure<AppSettings>(configuration.GetSection("AppSettings"))
                .Configure<AppSettings>(configuration.GetSection("ConnectionStrings"))
                .AddScoped<IEmailSender, EmailSender>()
                .AddScoped<IEmailService, EmailService>()
                .AddDbContext<TradingDbContext>()
                .AddAutoMapper(typeof(BusinessLayerServiceCollectionExtensions).Assembly);
                // other dependencies

            return services;
        }
Reasons:
  • Blacklisted phrase (0.5): thank you
  • Blacklisted phrase (1): Good morning
  • RegEx Blacklisted phrase (1): I want
  • RegEx Blacklisted phrase (1.5): Do you know how
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @Martin
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Konstantina