ASP.NET CORE Dependency Injection

Asked

Viewed 671 times

1

I have a situation that I don’t know how to solve. I have the following scenario: I have an ASP.NET CORE Webapi and a Class Library also in . NET CORE. Since the class library will be according to the Repository Pattern.

So I came across a question. I realized the interface DI/implementation in the web api but within the library class I can’t recover the connectionString I added in appsettings.json (within the library class), ends up returning null.

How can I recover connectionString from within the library class?

Edit1: The project is thus separated

  • Projteste.API (ASP.NET CORE)
  • Projteste.Repository (.NET CORE Classlibrary)

1 answer

6


I will show how I use in my project which is also done through the Repository Pattern and works perfectly.

Startup.Cs

Within the class Startup.cs create a property of type IConfigurationRoot, if there is no:

public IConfigurationRoot Configuration { get; }

That done, we go to the class builder 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;
}

Understand the .AddJsonFile passing the file "appsettings.json" which is where you usually put the connection string. I believe that your project is also like this.

Also note the addition of this line Configuration = builder.Build();.

Now to the method ConfigureServices also in class Startup.cs. Within the method, just below services.AddMvc(), put the following code:

services.AddSingleton<IConfiguration>(Configuration);

Once this is done, we have successfully configured the DI for the IConfigurationRoot.

Seurepositorio.Cs

Inside the class you want to access to connection string, create a variable of type string to guard his connection string:

private readonly string _connectionString;

Once this is done, create your class constructor as follows, informing IConfiguration as a parameter (it will be created through Dependency Injection):

public SuaClasseRepository(IConfiguration configuration)
{
    _connectionString = configuration.GetConnectionString("DefaultConnection");
}

Notice I used the configuration.GetConnectionString("DefaultConnection"); to get the connection string of the archive appsettings.json (defined in the Startup.Cs class) and that has the name DefaultConnection.

Below follows as is my file appsettings.json and it must follow with the same object names to avoid future problems:

  "ConnectionStrings": {
    "DefaultConnection": "myDatabaseConnectionString"
  }

Ready. Now you have access to your connection string in all the classes I created as shown above.

  • So by injecting the dependency into the API, I can see the Connection string that is in the appsettings.json of the API in the Class Library? In fact, ASP.NET Core 2.0 no longer configures the file by default appsettings.json?

  • Yes to both questions. But the appsettings.json file you can modify if you wish, add more than one Connection string, etc. I put the example of mine to you to see what it looks like and if it is with its string Connection inside.

  • Now I saw the structure of your project. It was not necessary to create another project only for Libraries. Since you did so, put an appsettings.json file in your tb Class Library and try to do what I reported above. I’ve never tested it that way to see if it works.

  • 1

    Thank you very much!! As you said, I wanted to separate things a little, even though I didn’t need to. But finally, injecting in the classStartup I can access the Library, just like you said.

  • Perfect! Good to know that in separate projects also works. I use the Repository Pattern, but all within the same project! Hug!

  • 1

    I see people commenting on separating, but unfortunately it takes a little work or not, I depend on your knowledge! Hug and thanks for the help again!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.