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

1 Answer 1

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

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

7 Comments

can you give a name of 2 packages i tried install Microsoft.Extensions.Configuration but failed
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?
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()
Yes, you're also missing nuget.org/packages/…
|

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.