1

I have a solution with multiple project using the same domain model. I thus created a class library that holds my domain models. This class library also contains other parameters that are used within my projects. I then add the reference to the class library in each of my projects. My class library also has some repository classes derived from this example.

I however have an issue with connecting to a database. I want my class library to be able to connect to the database since I defined my database context class in there, where I set my database sets. With a single project, I usually define my connection string in my web.config file. But the class library has no web.config file. How do I set my connection string?

EDIT

Say i have the constructor of my database context, mydbcontext, defined in the class library as

public mydbcontext() : base(ConfigurationManager.ConnectionStrings["DatabaseCon"].ConnectionString)
    {

    }

If I understanding this right, will it be OK to just set the name of the connection string of each project to "DatabaseCon"?

2
  • An assembly can locate the configuration file from its context, e.g. an assembly called from a web app will have access to the web.config. Commented Dec 29, 2012 at 16:38
  • @jpo - This is one way to do it, but now you data access library cannot be tested in isolation. Commented Dec 29, 2012 at 16:51

2 Answers 2

1

You don't.

Pass in the connection string as a dependency to whatever classes that require it.

You can encapsulate the access to it - but you should instantiate it in whatever program that uses this library. This program will hold the connection string in its configuration.

Sign up to request clarification or add additional context in comments.

2 Comments

This was an approach I did not consider. Do you please have an example?
@jpo - An example? You just pass in a string parameter to whatever needs it.
0

You should define the connection string in the web.config file of the application that is using the class library. As an alternative you could hardcode the connection string into the constructor of your DbConext inside the class library - pretty bad approach because you won't be able to modify it from the outside - for example you will have hard time managing different connection strings for the different environments - staging, production, ...

1 Comment

I already told you: you put the connection string inside the web.config of the web application that is using this library. That's the correct approach.

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.