2

My solution has 3 project:

  • Entity(include Dbcontext,...), target framwork .NetStandard 1.4, project type library
  • WebApi
  • WebUi

i want to create function migrate into Entity Project. In Entity project, i have a class TemporaryDbContextFactory

public class TemporaryDbContextFactory : IDbContextFactory<MyContext>
    {


        public ApplicationContext Create(DbContextFactoryOptions options)
        {
            var builder = new DbContextOptionsBuilder<MyContext>();
            builder.UseSqlServer("Server=(local)\\mssqllocaldb;Database=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa; Password=123456",
                optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyContext).GetTypeInfo().Assembly.GetName().Name));
            return new MyContext(builder.Options);
        }
    }

but in here i don't want to use hardcode connection string i tried to create appsetting for dynamic connection string :

public class MyContextFactory : IDbContextFactory<ApplicationContext>
    {
        public MyContext Create()
        {
            var environmentName =
                        Environment.GetEnvironmentVariable(
                            "Hosting:Environment");

            var basePath = AppContext.BaseDirectory;

            return Create(basePath, environmentName);
        }

        public MyContext Create(DbContextFactoryOptions options)
        {
            return Create(
                options.ContentRootPath,
                options.EnvironmentName);
        }

        private MyContext Create(string basePath, string environmentName)
        {
            var configuration = new Configuration();
            configuration.AddJsonFile(“config.json”);
            var emailAddress = configuration.Get("emailAddress");

            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environmentName}.json", true)
                .AddEnvironmentVariables();


            var config = builder.Build();

            var connstr = config.GetConnectionString("(default)");

            if (String.IsNullOrWhiteSpace(connstr) == true)
            {
                throw new InvalidOperationException(
                    "Could not find a connection string named '(default)'.");
            }
            else
            {
                return Create(connstr);
            }
        }

        private MyContext Create(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentException(
                    $"{nameof(connectionString)} is null or empty.",
                    nameof(connectionString));

            var optionsBuilder =
                new DbContextOptionsBuilder<MyContext>();

            optionsBuilder.UseSqlServer(connectionString);

            return new MyContext(optionsBuilder.Options);
        }
    }

i stuck in create a instance of this

var configuration = new Configuration();

the entity project doesn't have any reference to Microsoft.Extensions.Configuration I don't know how to add this because of I can't find it. please help me add this reference or suggest me a different way

astef
  • 8,575
  • 4
  • 56
  • 95
beginerdeveloper
  • 785
  • 4
  • 17
  • 43

1 Answers1

2

This is a new configuration framework which you'll like after get used to it:

var configuration = new ConfigurationBuilder()
   .AddJsonFile("config.json")
   .Build();
var emailAddress = configuration.GetValue<string>("emailAddress");

You'll need the following nuget packages to be installed: Microsoft.Extensions.Configuration.Json Microsoft.Extensions.Configuration.ConfigurationBinder

If you don't see it, be sure you're using the right feed. Look at Package Source combobox of a Package Manager, it should be nuget.org.

Also, be sure that config.json configuration file is copied to the output:

{
   "emailAddress" : "[email protected]"
}

Regarding connection strings specifically, look at this sample: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings#aspnet-core

astef
  • 8,575
  • 4
  • 56
  • 95
  • can you give a name of 2 packages i tried install Microsoft.Extensions.Configuration but failed – beginerdeveloper Sep 27 '17 at 09:18
  • 1
    I gave you the exact names: `Microsoft.Extensions.Configuration.Json` and `Microsoft.Extensions.Configuration.ConfigurationBinder`. Why did you fail? What you've tried and what happened? – astef Sep 27 '17 at 09:20
  • 1
    https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/ https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Binder/ – astef Sep 27 '17 at 09:20
  • but now i got a new error 'IConfigurationBuilder' does not contain a definition for 'AddEnvironmentVariables' and no extension method 'AddEnvironmentVariables' accepting a first argument of type 'IConfigurationBuilder' could be found (are you missing a using directive or an assembly reference?) complier error here : var builder = new ConfigurationBuilder() – beginerdeveloper Sep 27 '17 at 09:25
  • 1
    Yes, you're also missing https://www.nuget.org/packages/Microsoft.Extensions.Configuration.EnvironmentVariables/ – astef Sep 27 '17 at 09:26
  • thank you so much it's working well right now, but can i ask you other question. in my Web Api i have already had key "ConnectionString" how can i pass it to Entity Project – beginerdeveloper Sep 27 '17 at 09:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155405/discussion-between-beginerdeveloper-and-astef). – beginerdeveloper Sep 27 '17 at 09:39