从Startup.Cs中的Configure方法中获取应用程序目录

时间:2016-08-05 14:43:49

标签: c# asp.net-core

您不能在EF7上使用与SQLite相关的连接字符串,因此我需要一种方法在配置DBContext的ConfigureServices Routine中从Startup.cs中获取应用程序目录。

知道如何使用.NetCoreApp库吗?

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        //Figure out app directory here and replace token in connection string with app directory.......    

        var connectionString = Configuration["SqliteConnectionString"];

        if (string.IsNullOrEmpty(connectionString))
            throw new Exception("appSettings.json is missing the SqliteConnectionString entry.");
        services.AddDbContext<MyContext>(options =>
        {
            options.UseSqlite(connectionString, b => b.MigrationsAssembly("xyz.myproject.webapp"));

        });
    }

4 个答案:

答案 0 :(得分:6)

您可以将环境存储在本地属性中,然后您可以访问它以获取这样的基本路径:

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);


    Configuration = builder.Build();

    environment = env;
}

public IHostingEnvironment environment { get; set; }
public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // you can access environment.ContentRootPath here
}

答案 1 :(得分:3)

您可以使用以下命令获取应用程序基目录:

AppContext.BaseDirectory;

答案 2 :(得分:1)

对于函数应用,从 IFunctionsHostBuilder 对象获取上下文然后访问 ApplicationRootPath 对我有用:

public class ContainerConfig : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var context = builder.GetContext();

        ConfigureAppSettings(builder.Services, context);

        ...
    }

    public void ConfigureAppSettings(IServiceCollection services, FunctionsHostBuilderContext context)
    {
        ...

        var config = new ConfigurationBuilder()
            .SetBasePath(context.ApplicationRootPath)
            ...
    }
}

答案 3 :(得分:0)

只需在需要获取路径的地方使用依赖注入。

实施例

ValueController(..., IHostingEnvironment env)
{
Console.WriteLine(env.ContentRootPath);
...
}