0

Here is my asp.net core project structure

1- ASP.NET CORE Web API (contains aspsettings.json)

"ConnectionStrings": {
    "DefaultConnection": "Server=(local)\\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"

  }

2-SERVICES Project (Web API Call method from Services Project)
3-REPOSITORY Project (Services call method from Repository Project and Repository Project include the DATA Project where all the models are)

4-DATA Project where it's contain all the model with code first

public class TtEntities : DbContext
    {

        public virtual DbSet<RoomMessage> RoomMessage { get; set; }
        public virtual DbSet<UserRoom> UserRoom { get; set; }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
           optionsBuilder.UseSqlServer(@"Server=(local)\SQLEXPRESS;Database=testdb;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
....

As you can see, I hardcoded the connection on the method OnConfiguring which is not the best practice for sure.

Is there a way to pass the connection string from the configuration file of the Web API Project?

Is update database command will still work if we pass the connection from the file aspsettings.json from web api project ?

Thanks a lot

1
  • 1
    Can you provide code of creating TtEntities instance in ASP.NET CORE Web API? Did you use DI for this? Commented Dec 9, 2017 at 6:47

2 Answers 2

2

A simple solution is like this:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
}

Consider how DefaultConnection is used in line 13. Also a sample appsettings is like as follow:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication5;"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

DI solves this problem perfectly and .NET Core 2.0 has Microsoft DI thats provides clearly experience with DI.

oh, lets starts(i think that DATA Project and REPOSITORY Project should be one)

from REPOSITORY Project change your REPOSITORYClass to

    public class REPOSITORYClass 
    {
        private readonly TtEntities _db;

        public REPOSITORYClass (TtEntities db){
            _db = db;
        }

        //some your staff of REPOSITORYClass thats uses _db
    }

now go to SERVICES Project

lets change some service that uses REPOSITORYClass

public class SomeService
    {
        private readonly REPOSITORYClass _repo;

        public SomeService (REPOSITORYClass repo){
            _repo = repo;
        }

        //other staff of SomeService thats uses _repo
    }

after that go to ASP.NET CORE Web API startup file and add to

public void ConfigureServices

        // Get connection of your repo
        string connection = Configuration.GetConnectionString("DefaultConnection");
        // add TtEntities as service
        services.AddDbContext<TtEntities>(options =>
                        options.UseSqlServer(connection));

//add your repo
        services.AddTransient<REPOSITORYClass>();
//add your service
        services.AddTransient<SomeService>();

now go to the contoller thats uses your SomeService

    public class SomeController: Controller
        {
            private readonly SomeService _someService;

            public SomeController(SomeService someService){
                _someService = someService;
            }

            //And use whatever your wants from your service that injected with deps of repo and injected db entity with connection
            public string SomeMethod()
            {
                 return _someService.SomeMethod();
            }
        }

And use whatever your wants from your service that injected with deps of repo and injected db entity with connection

thats all

PS also recommend to read this Introduction to Dependency Injection in ASP.NET Core

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.