简体   繁体   English

在 ASP.Net Core MVC 数据层中获取连接字符串

[英]Getting Connection String in ASP.Net Core MVC data layer

I am using the code below to retrieve the connection string and it works fine.我正在使用下面的代码来检索连接字符串,它工作正常。 However, the configuration object has to be passed through the layers.但是,配置 object 必须通过层。 Previous versions of.Net would allow me to get the connection string directly in the data layer.以前版本的 .Net 将允许我直接在数据层中获取连接字符串。 So can I still do that (and how do I do that) or do I need to pass the configuration object through the application as I do now?那么我仍然可以这样做(以及我该怎么做)还是需要像现在一样通过应用程序传递配置 object?

In startup.cs在启动.cs

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddSingleton(_ => Configuration);
   ...
}

MyController.cs我的控制器.cs

public class MyController : Controller
{
  protected readonly IConfiguration Configuration;

  public MyController(IConfiguration configuration)
  {
     Configuration = configuration;
  }

  public IActionResult ListRecords()
  {
      DatabaseContext ctx = new DatabaseContext(Configuration);
      return View();
  }
}

DatabaseContext.cs数据库上下文.cs

public class DatabaseContext : DbContext
{
   private readonly IConfiguration config;
   public DatabaseContext(IConfiguration config)
   {
      this.config = config;
   }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
      optionsBuilder.UseSqlServer(config["ConnectionStrings:Dev"]);
   }
}

Having to explicitly inject IConfiguration is usually seen as a code smell and indicates design issues.必须显式注入IConfiguration通常被视为代码异味并表明存在设计问题。

Take advantage of dependency injection利用依赖注入

public class MyController : Controller {
    DatabaseContext context;

    public MyController(DatabaseContext context) {
        this.context = context;
    }

    public IActionResult ListRecords() {
        //...use context here
        return View();
    }
}

and inject the database options instead并注入数据库选项

public class DatabaseContext : DbContext {    
    public DatabaseContext(DbContextOptions<DatabaseContext> options): base(options) {
        //...
    }
}

Then it is only a matter of configuring the context at startup那么只需要在启动时配置上下文即可

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services) {
    // ...

    services.AddDbContext<DatabaseContext>(options => 
        options.UseSqlServer(Congiguration.GetConnectionString("Dev"));

    // ...
}

Typically the pattern I've used for setting up DBContext, is to configure at startup.通常,我用于设置 DBContext 的模式是在启动时进行配置。

So if this is startup.cs:所以如果这是startup.cs:

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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)
        {
            var sqlConnString = Configuration.GetConnectionString(dbConnectionStringSettingsName);

            services.AddDbContext<DatabaseContext >(opt => opt.UseSqlServer(sqlConnString));

Also, if you pass your context as a service reference, you shouldn't need to give it IConfiguration.此外,如果您将上下文作为服务引用传递,则不需要为其提供 IConfiguration。

    private readonly DatabaseContext _context;       

    public MyController(DatabaseContext context)
    {
        _context = context;
    }
    public IActionResult ListRecords()
    {
      var dbresults = _context.Table.ToList();
      return View(dbresults );
    }

use nugget packaeges使用金块包

Install-Package Microsoft.Extensions.Configuration.Abstractions

 Install-Package Microsoft.Extensions.Configuration

and then Inject IConfigurationSection in the web application.然后在 web 应用程序中注入IConfigurationSection

https://github.com/geeksarray/read-appsettings-json-in-net-core-class-library-using-dependency-injection https://github.com/geeksarray/read-appsettings-json-in-net-core-class-library-using-dependency-injection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM