Search code examples
c#discorddiscord.net

How to access a configuration file located in one project from another project


This is my database context design factory class within my current project. To connect to my database, it requries my connection string which is stored in a configuration file (_config.json).

public class HiromiContextDesignFactory : IDesignTimeDbContextFactory<HiromiContext>
{
    public HiromiContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath() // What is the path
            .AddJsonFile("_config.json")
            .Build();

        var builder = new DbContextOptionsBuilder<HiromiContext>()
            .UseNpgsql(configuration["Connections:Postgre"]);

        return new HiromiContext(builder.Options);
    }
}

However, my configuration file is located in the root directory of another project. Therefore, I am unsure as to what path I should use in the SetBasePath() method to access this file. How should I tackle this issue?


Solution

  • Looks like this issue was simple. The answer provided by @aDisplayName worked perfectly fine and is an acceptable solution if you are facing the same problem. However, Microsoft actually recommends the usage of user secrets for storing sensitive data in development.

    Since a database context design factory class is only required for Migrations (it has nothing to do with the running of the application or database connection context, that is for your regular context class that inherits from DbContext) I can safely store my connection string as a user secret.

    I have linked the documentation above for doing so, but here is quick summary of what I did.

    Navigate to the project that contains your design factory class and run the commands

    dotnet user-secrets init
    dotnet user-secrets set "Connections:Postgres" "CONNECTION_STRING"
    

    Then, call the AddUserSecrets<T>() method on your configuration builder rather than setting a base path. The configuration builder should look like this instead.

    var configuration = new ConfigurationBuilder()
                .AddUserSecrets<HiromiContext>() // This should be the name of the class that inherits from DbContext.
              //.AddUserSecrets(Assembly.GetEntryAssembly()) You can also do this if your database context and database design factory classes are in the same project, which should be the case 99% of the time
                .Build();