3

Connection strings exist in appsettings.json in an ASP.Net MVC Core Project. I also have a Class Library Project in the same solution and there I want to get the connection string of web project, I am unable to find help in official resources, how can I achieve this?

Update: The class library is of .Net 4.6.1, also in the ASP.Net Core Project I am targeting .Net 4.6.1.

7
  • 1
    Add reference System.Configuration in your Class library project. Commented Dec 27, 2016 at 6:10
  • 3
    Please have a look at Get connection string in class library project in a solution Commented Dec 27, 2016 at 6:21
  • @Abhay Sure. Thanks. Commented Dec 27, 2016 at 6:24
  • @Abhay: Don't ignore the tags. Question is about ASP.NET Core, which doesn't support confiugration via web.config anymore. One should use the dependency injection pattern all the way and the IOptions<T>pattern Commented Dec 27, 2016 at 8:22
  • 2
    Possible duplicate of .NET Core get connection string from appsettings.json Commented Dec 27, 2016 at 10:17

1 Answer 1

2

Register Configuration in Startup.cs

public void ConfigureServices(IServicesCollection services) 
{
     services.AddSingleton(Configuration);
}

Then you can inject it in controller or any other library project class

public HomeController(IConfigurationRoot Configuration)
{
            this.Configuration= Configuration;
}

Then you can get connection string as you get in Startup.cs

Configuration.GetConnectionString("DefaultConnection")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.