Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I place the connection string in an ASP.NET Core library project that has no startup file?

I have asp.net core library project.

I want to add connection string to it. I don't have startup class in this. Where I need to place connection string and how to fetch it?

like image 478
Asif Hameed Avatar asked Feb 02 '17 12:02

Asif Hameed


1 Answers

In dotnet core you can manage configuration using json files, which is one in many ways to configure your application.

According to the dotnet core configuration documentation you can simply do (copied from link reference)

using Microsoft.Extensions.Configuration;
using System;
using System.IO;

// Add NuGet <package id="Microsoft.Extensions.Configuration" and
// <package id="Microsoft.Extensions.Configuration.Json"
// .NET Framework 4.x use the following path:
//.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), @"..\.."))

public class Program
{
    static public IConfigurationRoot Configuration { get; set; }
    public static void Main(string[] args = null)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

        Console.WriteLine($"option1 = {Configuration["option1"]}");
        Console.WriteLine($"option2 = {Configuration["option2"]}");
        Console.WriteLine(
            $"option1 = {Configuration["subsection:suboption1"]}");
    }
}

Then in your appsettings.json file you can add:

{
    "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
    },
}

And access it in code using Configuration.GetConnectionString("BloggingDatabase")

I can recommend also reading the dotnet core documentation regarding connection strings

EDIT: As the commentors mention on your post, don't add connection strings and config files to your library code - do this from your console application or the web application!

Additional forms of configuration for dotnet core includes user secrets, environment variables and perhaps XML files or other forms of storage, as pointed out in the comments

like image 130
nover Avatar answered Sep 20 '22 07:09

nover