I'll show you how to use it in my project, which is also done through Repository Pattern
and works perfectly.
Startup.cs
Within class Startup.cs
create a property of type IConfigurationRoot
, if it does not exist:
public IConfigurationRoot Configuration { get; }
Once this is done, let's go to the constructor of class Startup.cs
. Here your file should look like the code below.
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
Environment = env;
}
Realize the .AddJsonFile
by passing the file "appsettings.json"
which is where it normally places connection string
. I think your project looks that way too.
Note also the addition of this line Configuration = builder.Build();
.
Now we go to the ConfigureServices
method also in the Startup.cs
class. Within the method, just below% with_of%, put the following code:
services.AddSingleton<IConfiguration>(Configuration);
Once this is done, we have successfully configured the DI for services.AddMvc()
.
Seurespositorio.cs
Within the class you want to access IConfigurationRoot
, create a variable of type connection string
to store your string
:
private readonly string _connectionString;
Once this is done, create the constructor of your class as follows, informing connection string
as parameter (it will be created through Dependency Injection):
public SuaClasseRepository(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection");
}
Notice that I used IConfiguration
to search for configuration.GetConnectionString("DefaultConnection");
of file connection string
(we defined it in class Startup.cs) and that it has the name appsettings.json
.
Below is how my DefaultConnection
file is, and it should follow the same object names to avoid future problems:
"ConnectionStrings": {
"DefaultConnection": "myDatabaseConnectionString"
}
Ready. You now have access to your appsettings.json
in all classes you create as I've shown above.