Config connection string in .net core 6 - c#

I'm attempting to connect to my ASP.NET Core Web API application (.NET 6 in Visual Studio 2022 Preview) with SQL Server. And I tried to use the following code to configure the connection string in the Startup class as I used to.
services.AddDbContext<DEMOWTSSPortalContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
But in .NET 6, I recognize that Startup and Program classes are merged into one class. And the above code is not usable in .NET 6. AddDbContext is not recognized. So do you have any idea or documentation about this update, and how to configure connection strings in .NET 6?

Configuration.GetConnectionString(string connName) in .NET6 is under builder:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
also AddDbContext() is under builder.Services:
builder.Services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

.Net 6 Simplifies a lot of a tasks and introduces WebApplicationBuilder which in turn gives you access to the new Configuration builder and Service Collection
var builder = WebApplication.CreateBuilder(args);
Properties
Configuration : A collection of configuration providers for the application to compose. This is useful for adding new configuration sources and providers.
Environment : Provides information about the web hosting environment an application is running.
Host : An IHostBuilder for configuring host specific properties, but not building. To build after configuration, call Build().
Logging : A collection of logging providers for the application to compose. This is useful for adding new logging providers.
Services : A collection of services for the application to compose. This is useful for adding user provided or framework provided services.
WebHost : An IWebHostBuilder for configuring server specific properties, but not building. To build after configuration, call Build().
To add a DbContext to the Di Container and configure it, there are many options however the most straightforward is
builder.Services.AddDbContext<SomeDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
Nugets packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer to use UseSqlServer

You can try to read in your controller like this..
private readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
_logger = logger;
string _configuration = configuration.GetSection("connectionStrings").GetChildren().FirstOrDefault(config => config.Key == "Title").Value;
}
NOTE: You can get the value based on the key provided above.

Install Packages
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.FileExtensions.dll
Microsoft.Extensions.Configuration.Json.dll
Add Name Spaces in Controller
using Microsoft.Extensions.Configuration;
using System.IO;
Add Code in
Controllervar objBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
In appsettings.json Add Code:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

Related

.NET Core 6 Program.cs injecting and configuring EF Core Migrations referenced from a different project

I am attempting to setup a simple solution that consists of a ASP.NET Core 6 Web Api project and a .NET Core class library project using EF Core 7 and running into problems setting up the DBContext in the Program.cs file and running EF migrations.
Here is a copy of my Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
using MyEFCoreTestProject.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
builder.Services.AddDbContext<MyDbContext>(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Here is a copy of my DBContext in the other project.
using Core;
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers{ get; set; }
public DbSet<CustomerAddress> CustomerAddresses { get; set; }
}
In my class library project where the DBContext exists I have the following nuget packages installed:
Microsoft.EntityFrameworkCore 7.0.2
Microsoft.EntityFrameworkCore.Design 7.0.2
Microsoft.EntityFrameworkCore.Relational 7.0.2
Microsoft.EntityFrameworkCore.SqlServer 7.0.2
Microsoft.EntityFrameworkCore.Tools 7.0.2
No matter how I attempt to run the migration I get the following error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'MyDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyEFCoreTestProject.MyDbContext]' while attempting to activate 'MyEFCoreTestProject.MyDbContext'.
This is just what I have been running into while trying to do what I believe is a simple dependency registration. What I really would like to do is create a DbContext with a constructor that allows me to pass the connection string and some other flags in as parameters but my first step is just to get things working so I will have to tackle that next after this issue is solved.
Also I am not opposed to a DbContextFactory but I have been unable to find a working example that I could follow in .Net Core 6.
Any help anyone could provide is greatly appreciated.

How should I correct the registerations of my Scoped Services in my Blazor server app after upgrading to Visual Studio 2022 and .NET 6?

I have a Blazor server app that is built on .NET Core 3.1. The app is working without problem.
After I updated from VS 2019 to VS 2022 and also .NetCore3.1 to Net6.0 I noticed that my scoped services are not running any more. I have read that the registration of the services are a little bit different in .NET6.0, but I couldn't make it working.
My actual registration is in Startup.cs (that is merged with Program.cs in .NET6.0 as I understood)
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<ConnectService>();
services.AddScoped<TagService>();
}
I tried to register in Pogram.cs like below but didn't work
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<ConnectService>();
builder.Services.AddScoped<TagService>();
}
I am injecting the service in my razor page as follows (that I haven't changed)
#page "/connect2"
#inject TagService TagService
You can get the basic structure with the templated solution.
dotnet new blazorserver -o <OutputDirectory>
It should look something like this
//declare web
var builder = WebApplication.CreateDefault(args)
//add services
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<ConnectService>();
builder.Services.AddScoped<TagService>();
//then build app
var app = builder.Build();
//add any neccessary routing middleware
//then run
app.Run()

How to Implement Application Insights Telemetry on ASP.NET 4.7.1 that uses Appsettings.json?

How can I configure application insights telemetry for an asp.net framework 4.7.1 web application that uses appsettings.json configuration files? I tried checking the Microsoft documentation but it just shows setup for ASP.NET apps that use xml-based configuration.
EDIT: Here is the part of the Startup.cs file that shows I am using appsettings.json.
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
SCENARIO - 1
This works in case of .net framework 4.7.1 web application which have no auto generated appsettings.json file.
Navigate to your Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close
In applicationinsights.config file, while Adding Application Insights automatically we need to add instrumentation key to ApplicationInsights.config before closing the </ApplicationInsights> tag file.
<InstrumentationKey>"your-instrumentation-key-goes-here"</InstrumentationKey>
And then update each Microsoft.ApplicationInsights NuGet package to the latest stable release by navigating to Project > Manage NuGet Packages > Updates.
If Adding Application Insights Automatically isn't working, then you can try manually from HERE.
REFERENCE : Configure monitoring for ASP.NET with Azure Application Insights
SCENARIO - 2
You can have application Insights configuration set from your appsettings.json file when you have one in your project
Navigate to your appsettings.json file and add your instrumentation key for your application Insights like mentioned inthe below reference.
Application Insights comes in the form of a Nuget package. Review the .csproj file of the web project and look for the Application Insights package added.
Now navigate to your startup.cs project and add services.AddApplicationInsightsTelemetry(Configuration); to your ConfigureServices method.
Navigate to Configure method and add
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
REFERENCE : Monitoring Applications using Application Insights

Get assemblies configuration

I have a class library that is used as a nuget package. The Nuget package will be used in one or more Web Api's.
I my class library, I want to be able to read the web api's configuration settings.
Can this be done with the Assembly.GetCallingAssembly(), which in this case is my web api?
The reason is that the web api's will have a connectionString that they get from Azure Key vault, and I want to read this connectionString in my class library(nuget package). I don't want want to pass the connectionString as a parameter to the nuget package. It should be fixed automagic.
I have tried something like this in my class library:
string path = Assembly.GetCallingAssembly().Location; // the web api
var config = ConfigurationManager.OpenExeConfiguration(path);
But I can't find the connectionString from the key vault here.
Here is the code in my Startup.cs in one of the web api's where azure key vault is added
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json") appsettings.json in.
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>(); M
}
builder.AddKeyVaultConfiguration();
Configuration = builder.Build();
}
The connectionstring looks like this: Azure:Database:ConnectionString, and now I want to access this in my nuget package(Class library)

Specifying HostingEnvironment when running EF 7 migration

I have set my connection strings for my DbContexts as per my application environment. So in my Startup.cs I have
public Startup(IHostingEnvironment env, IApplicationEnvironment app)
{
Configuration = new ConfigurationBuilder(app.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", false)
.AddEnvironmentVariables()
.Build();
}
This configuration gets injected into my DbContexts as follows
public MyDbContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
var connString = Configuration.Get("SqlDb:ConnectionString");
builder.UseSqlServer(connString);
}
And thus I can use my project in various environments as I please (by setting ASPNET_ENV in app or host settings)
However when I run ef migrations (for obvious reasons) I cant specify the HostingEnvironment at all, the startup class looks for a file called "config..json" since the environment name is missing. Is there a way around this or a workaround that I can do? For now whenever I run migrations I have to hardcode the connection strings when I run migrations
For interest sake I run migrations from powershell using the dnx . ef command
So in summary is it possible to specify my host environment via the command or do any other kind of workaround to specify my environment when running these commands?
How migrations discovers services for migrations will be changing in upcoming versions of EF.
This is a WIP. See EF7's Wiki - Design Meeting Notes (September 17, 2015) and Issue 2294
The --environment option was added with 7f48d0c.

Categories

Resources