简体   繁体   中英

Enterprise Library Database connection from web.config into Asp.net 5.0 Core vnext MVC6

If using Microsoft.Practices.EnterpriseLibrary it uses the web.config file to set the database configuration and connection. How would this work with MVC6 .Net Core/Vnext? To get this working? Does something need to be set on the Startup file??

<configSections>
<section name="dataConfiguration"    type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,   Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral,   PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
  </configSections>
<dataConfiguration defaultDatabase="MyDBConnectionString" />
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=MyDatabaseServer;Database=MyDatabase; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

{
 "Data": {
   "dataConfiguration": {
     "type":"Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
       "requirePermission": "false"
},
"DefaultConnection": {
  "ConnectionString": "Data Source=MyDatabaseServer;Database=MyDatabase; Integrated Security=SSPI;",
  "providerName": "System.Data.SqlClient"
 }
},

    public static Model.Record GetRecordByID(Int32 ID)
    {

        //Declare the variables
        Amendment obj = new Record();
        object xml = null;
        DbCommand dbCmd = null;
        Database db = null; 
        try
        {

            // Create the database object, using the default database service. The
            // default database service is determined through configuration.


            DatabaseProviderFactory factory = new DatabaseProviderFactory(new SystemConfigurationSource());
            DatabaseFactory.SetDatabaseProviderFactory(factory, false);


           db = DatabaseFactory.CreateDatabase();


             dbCmd = db.GetStoredProcCommand("spXMLGetRecordByID");

            db.AddInParameter(dbCmd, "RecordID", DbType.Int32, ID);
            db.AddInParameter(dbCmd, "@xml", DbType.Xml, 1);



            if (!xml.Equals(DBNull.Value))
            {


                obj = (Amendment)Deserialize(xml.ToString(), typeof(Record));
            }


        }
        catch (SqlException sqlEx)
        {
            // ExceptionUtility.SendError(sqlEx, "DAL", "GetRecordByID");
        }
        catch (Exception ex)
        {
            //ExceptionUtility.SendError(ex, "DAL", "GetRecordByID");

        }
        finally
        {
            // DALCleanUp(db, dbCmd);

        }

        return obj;

    }

For all people who are trying to use EnterpriseLibrary.NetCore in a ASP.NET Core project:

The configuration will only be read if you store it in a app.config file.

If you're migrating a project from ASP.NET to ASP.NET Core, you have to rename the web.config to app.config.

See also this: https://stackoverflow.com/a/50572248/7500260

To use the settings in appsettings.json (or any other json file) the first step is to add the file(s) to an IConfigurationRoot member variable in class Startup. This code is generated for you when you create a project with the ASP.NET 5 template.

public IConfigurationRoot Configuration { get; set; }

public class Startup
{
    var builder = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

After that you can use the IConfigurationRoot member variable to access individual values from the json file.

this.Configuration["Data:DefaultConnection:ConnectionString"]

You can also get sections of the configuration file if you have a class that matches the json.

Public class DataConfiguration
{
    public string type { get; set; }
    public bool RequirePermission { get; set; }
}

In the ConfigureServices() method of class Startup, add that class with the values from the json file to the IoC container.

services.Configure<DataConfiguration>(Configuration.GetSection("Data:dataConfiguration"));

This is how you access those settings in the Configure() method of class Startup

DataConfiguration dataConfig;
bool requirePermission;

dataConfig= app.ApplicationServices.GetService<DataConfiguration>();
requirePermission = dataConfg.RequirePermission ;

You can also access the settings from any class that is called by the framework (because your instantiated class is in the IoC container).

public class MyController : Controller
{
    private IOptions<DataConfiguration> dataConfig;

    public MyController(IOptions<DataConfiguration> dataConfig)
    {
        this.dataConfig= dataConfig;
    } 

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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