Get Multiple Connection Strings in appsettings.json without EF

前端 未结 3 782
天命终不由人
天命终不由人 2021-01-12 08:08

Just starting playing with the .Net Core RC2 by migrating a current MVC .Net app I developed. It looks like to me because of the way that configuration is handled with apps

3条回答
  •  清歌不尽
    2021-01-12 08:20

    There are a couple of corrections that I made to Adem's response to work with RC2, so I figured I better post them.

    I configured the appsettings.json and created a class like Adem's

    {
        "ConnectionStrings": {
          "DefaultConnectionString": "Default",
          "CustomConnectionString": "Custom"
        }
    }
    

    and

    public class ConnectionStrings
    {
        public string DefaultConnectionString { get; set; }
    
        public string CustomConnectionString { get; set; }
    }
    

    most of Adem's code comes out of the box in VS for RC2, so I just added the line below to the ConfigureServices method

    services.Configure(Configuration.GetSection("ConnectionStrings"));
    

    The main missing point is that the connection string has to be passed to the controller (Once you’ve specified a strongly-typed configuration object and added it to the services collection, you can request it from any Controller or Action method by requesting an instance of IOptions, https://docs.asp.net/en/latest/mvc/controllers/dependency-injection.html)

    So this goes to the controller,

    private readonly ConnectionStrings _connectionStrings;
            public HomeController(IOptions connectionStrings)
            {
                _connectionStrings = connectionStrings.Value;
            }
    

    and then when you instantiate the DAL you pass the appropriate connectionString

    DAL.DataMethods dm = new DAL.DataMethods(_connectionStrings.CustomConnectionString);
    

    All the examples show this, they just don't state it, why my attempts to pull directly from the DAL didn't work

提交回复
热议问题