1

I'm using .net core 2.0 and my structure is like that basically: I have 20 Web Api project and one class library (DbContext) project. Web Api projects have Startup.cs. But class library hasn't got Startup.cs. Where should I write the connection string? Because class library has no app.config or Startup.cs. If I write in Startup.cs of API's, then I have to write connectionString 20 times. This is not acceptable. I wrote using DbContextOptions like below but I'm not sure, it's the best way. What is the best way for this?

public class MyDbContext : DbContext
{
    private readonly IAuditHelper auditHelper;

    public MyDbContext(DbContextOptions<MyDbContext> options, IAuditHelper auditHelper)
        : base(GetOptions())
    {
        this.auditHelper = auditHelper;
    }

    private static DbContextOptions GetOptions()
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "server=asdf; database=asdf; user id=asdf; password=asdf").Options;
    }

    public async Task<int> SaveChangesWithoutAuditAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        return (await base.SaveChangesAsync(true, cancellationToken));
    }
}
4
  • no app.config but app.json :-) learn.microsoft.com/en-us/ef/core/miscellaneous/… Commented Oct 23, 2018 at 14:44
  • Thanks for your reply @LaurentLequenne. The main thing what I want to learn is using DbContextOptions is best way or is there any better way? Commented Oct 23, 2018 at 14:54
  • 1
    If this is a class library, you should leave the injection of the configuration to the consumer of the library via whatever dependency-injection means they would like to use, rather than hiding it inside your library as an implementation detail Commented Oct 23, 2018 at 15:06
  • Thanks a lot your answer and advice @MartinCostello Commented Oct 23, 2018 at 18:25

1 Answer 1

2

You would create an appsettings.json file, which would have the one or many connections declared.

{
     "ConnectionStrings": {
          dbExampleSystemConnection: "...",
          dbSampleSystemConnection: "..."
     }
}

Once you have defined your connection in your appsettings.json you would need to build a configuration and also configure Entity Framework inside the Service Collection to build your Service Provider. To add the appsettings.json you need to do the following:

public static IConfiguration BuildConfigurationProvider() => new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", false, true)
     .Build();

Then you need to create your Service Collection, I expanded mine out a bit but in essence you need the following:

public class ApplicationProvider
{
     public ApplicationProvider() => Configuration = ApplicationConfigurationProvider.BuildConfigurationProvider();

     public void StartApplication()
     {
          var serviceCollection = new ServiceCollection().AddSingleton(configuration => Configuration);
          var serviceProvider = ApplicationServiceProvider.BuildServiceProvider(serviceCollection);

          ...
     }
}

So you have defined and added the configuration, so you have access to your built configuration. However, for for you to globally define you would need to do the following in your Service Collection:

 services.AddDbContext<BloggingContext>(options => options.UseSqlite(Configuration.GetConnectionString("dbSampleSystemConnection"));

In my console application I created a series of providers, but you should have a bulk of this defined in your Web Api Project already. My console application is using the default DI container for Core.

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

1 Comment

Thanks @Greg. I will try this 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.