在Asp.Net Core应用中使用连接字符串的最佳实践

问题描述 投票:0回答:2

我不能使用EF,因为它不适用于Oracle(或者我发现的教程已经过时且无法使用。)>

我正在计划使用ODP.Net或devart的驱动程序。

使用来自appsettings.json的连接字符串的最佳方法是什么?

已经看过很多教程不完整或不能与Asp.Net Core 3.1一起使用]

我的控制器

public class ReportController : Controller
{
    private readonly ConnectionString myString;
    public ReportController(IOptions<ConnectionString> connectionString)
    {
        myString = connectionString.Value;
    }

    public ActionResult Reporting_Totals()
    {
        string connectionString = myString.ToString();
        DataTable dt = new DataTable();
        using (OracleConnection oracleConnection = new OracleConnection())
        return View();
    }

ConnectionString类

public class ConnectionString
{        
    private string connectionString { get; set; }
    // enable set in singleton property instance to work correctly.
    //public static ConnectionString Instance { get; set; } = new ConnectionString();

    //public string DatabaseConnection { get; set; }
}

我的创业班

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        //configuration.GetSection("ConnectionString").Bind(ConnectionString.Instance);
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<ConnectionString>(Configuration.GetSection("ConnectionStrings"));
        services.AddControllersWithViews();
    }

我的appsettings.json

  "ConnectionStrings": {
    "DEV": "Server=myServer;Database=myDb1;Trusted_Connection=True;",
    "PROD": "Server=myServer;Database=myDb2;Trusted_Connection=True;"

我无法使用EF,因为它不适用于Oracle(或者我发现的教程已经过时且无法使用)。我打算使用ODP.Net或devart的驱动程序。什么是使用...

c# asp.net-core model-view-controller appsettings
2个回答
0
投票

我相信最好的方法是使用依赖注入:


0
投票

您是否有特殊原因需要特殊的ConnectionString class?如果只想获取连接字符串,则可以直接注入IConfiguration并仅使用GetConnectionString扩展方法。

© www.soinside.com 2019 - 2024. All rights reserved.