Как написать строку подключения для моего ядра asp.net MVC - PullRequest
1 голос
/ 12 октября 2019

Хотя я посмотрел на многие решения, но я не могу применить или понять, как использовать строку подключения в моей основной программе mvc asp.net.

Это мой файл appsettings.json:

 {
  "Logging": {
    "Debug": {
      "LogLevel": {
        "Default": "Information"
      }
    },
    "AllowedHosts": "*",
    "ConnectionString": {
      "connectionString": "Server=W1571415\\MSSQLSERVER01;Database=***********;User 
       Id=*********;Password=***********;"
        } },
         "dependencies": {
         "Microsoft.Extensions.Caching.Memory": "1.0.0",
         "Microsoft.AspNetCore.Session": "1.0.0"
        }
       }

МОЙ код файла startup.cs:

using HospitalApp.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Globalization;

//This file is for app behaviour
namespace HospitalApp
{
    /// <summary>
    /// Startup class contains the methods scuh as ConfigureServices which are used to configure the environment in which the application is running.
    /// </summary>
    public class Startup
    {
        private readonly ILogger _logger;

        /// <summary>
        /// The control from the Program.cs when it encounters the .UseStartup() comes here.It uses the parameters configuration of the type IConfiguration and logger of the type ILogger.
        /// </summary>
        public Startup(IConfiguration configuration, ILogger<Startup> logger)
        {
            Configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// This method Configuration is of the type IConfiguration.
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">services is of the type IServiceCollection which is used specify the contract of collection to service descriptors.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            ////services.AddSession(so =>
            ////{
            ////    so.IdleTimeout = TimeSpan.FromSeconds(60);
            ////});

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
                        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                        .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
            options => { options.ResourcesPath = "Resources"; })
                        .AddDataAnnotationsLocalization();

            //dependency injection
            services.AddSingleton<IDbRepository, DbRepository>();

            //_logger.LogInformation("Added TodoRepository to services");
            services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            services.AddSession();



        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">This is provides mechanism to confifure application's request pipeline.</param>
        /// <param name="env">Provides information about the webhsoting environment an application is running in.</param>
        /// <param name="loggerFactory">Represent a type used to configure the logging system.</param>
        /// <param name="logger">It is of the type ILogger which is a generic interface for logger.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ILogger<Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddFile("Logs/mylog-{Date}.txt");
                _logger.LogInformation("In Development environment");
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            var cultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("pt")
            };

            app.UseRequestLocalization(options => {
                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures = cultures;
                options.SupportedUICultures = cultures;
            });


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

И вместо этого я не использую файл DBContextвот мой файл Infrastrucutre, который содержит файлы IDbRepostiory и DbRepository. и я должен использовать эту строку подключения в файле DbRepostiory. Итак, как это сделать?

 namespace HospitalApp.Infrastructure
{

    /// <summary>
    /// This class is used to establish a data connection with the MS SQL Server.

    /// The connectionString specified here stores the Database name and the Data Source specifies the server name.
    /// </summary>
    public class DbRepository : IDbRepository
    {
        /// HERE I NEED TO SPECIFY THE CONNECTION STRING FROM APPSETTING.JSON FILE.

        //string connectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=HospitalDummy;Data Source=W1571415\\MSSQLSERVER01;Application Name=Hospital";
        string connectionString = @"Server=W1571415\MSSQLSERVER01;Database=HospitalDummy;User Id=hospitaluser;Password=abc@123;";

        /// <summary>
        /// This function is used to display all the Patients data.  
        /// The patient's data is taken in the form of a list.
        /// SqlConnection is used to specify the connection of the connectionString with the Database.
        /// Here the Stored procedure spGetAllPatients is taken which is used to display the Patients details.
        /// </summary>
        /// <returns>It returns the details of the patient's in the form of a List.</returns>
        public List<Patient> GetAllPatients()
        {
            List<Patient> lstpatient = new List<Patient>();

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("dbo.spGetAllPatients", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();

                    while (rdr.Read())
                    {
                        Patient patient = new Patient();
                        try
                        {
                            patient.PatientId = Convert.ToInt32(rdr["PatientId"]);
                            if (rdr["FullName"] != DBNull.Value)
                                patient.FullName = Convert.ToString(rdr["FullName"]);
                            if (rdr["Ailment"] != DBNull.Value)
                                patient.Ailment = Convert.ToString(rdr["Ailment"]);
                            if (rdr["Gender"] != DBNull.Value)
                                patient.Gender = Convert.ToString(rdr["Gender"]);
                            if (rdr["Status"] != DBNull.Value)
                                patient.Status = Convert.ToString(rdr["Status"]);
                            count = count + 1;

                            if (patient.Status == "Active")
                            {
                                lstpatient.Add(patient);
                            }
                        }
                        catch (Exception e)
                        {
                           Console.WriteLine("Records not displayed properly. ",e);
                        }
                    }

                    con.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failure in getting records properly. ", e);
                }
            }
}

This is the IDbRepostiory file for reference:



public interface IDbRepository
    {
        /// <summary>
        /// This function is used to get the list of all Patients.
        /// </summary>
        /// <returns>It has a return type of list i.e. the Patient data that will be returned will be in 
    the form of a list.</returns>
        List<Patient> GetAllPatients();
    }

Заранее благодарю за помощь.

1 Ответ

1 голос
/ 14 октября 2019

Обзор этого:

i. Убедитесь, что ваш DbRepository реализует интерфейс (IDbRepository, готово), так что он может быть вызван как служба и содержит конструктор, который используется для получения любых данных конфигурации

ii. Откройте appsettings.json из Startup.cs , чтобы получить данные конфигурации json

iii. Из Startup.cs создать DbRepository в качестве IDbRepository службы и передать строку подключения в качестве параметра

If DbRepository унаследованный от DbContext , вы можете добавить конструктор, подобный этому

public DbRepository(DbContextOptions<DbRepository> options) : base(options) 
{
}

Альтернатива, вот как вы можете вручную создать конструктор, и для хорошей меры я имеюдобавлен метод тестирования GetConnectionString ()

public class DbRepository : IDbRepository
{
    private string _connectionString;

    public DbRepository(string connection)
    {
        _connectionString = connection;
    }

    public string GetConnectionString()
    {
        return _connectionString;
    }
}

В Statup.cs посмотрите, как конструктор обращается к appsetting.json и сохраняет данныев поле Конфигурация

Посмотрите, как ConfigureServices вызывает службу IDbRepository и передает параметр

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using HospitalApp.Infrastructure;

namespace Test
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
                Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            string connectionString = Configuration["ConnectionString:connectionString"];
            //  this is how a class inheriting dbcontext can be called
            //  services.AddDbContext<DbRepository>(options => options.UseSqlServer(connectionString));
            //  or call IDbRepository as a custom service
            services.AddScoped<IDbRepository>(repository => new DbRepository(connectionString));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //  ... }
    }
}

Представьте, что ваш HomeController выглядит примерно так, принимая экземпляр сервиса IDbRepository через его конструктор, чтобы он мог получить доступ к хранилищу и передать егострока подключения вк ViewBag

public class HomeController : Controller
{
    private readonly IDbRepository _dbrepository;

    public HomeController(IDbRepository dbrepository)
    {
        _dbrepository = dbrepository;
    }

    [HttpGet]
    public ViewResult Home()
    {
        ViewBag.ConnectionString = _dbrepository.GetConnectionString();
        return View("Home");
    }
}

и Home.cshtml просто необходимо содержать следующее, чтобы продемонстрировать успех

<h1>ConnectionString</h1>
<b>@ViewBag.ConnectionString</b>

enter image description here

Подтверждено в тестовом проекте - впервые я создал сервис, который принимает параметр (ранее только что использовался dbcontext), так что было бы хорошо посмотреть на это - надеюсь, это поможет!

Вот мойappsettings.json

{
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        }
    },
    "AllowedHosts": "*",
    "ConnectionString": {
        "connectionString": "Server=W1571415\\MSSQLSERVER01;Database=***********;UserId=*********;Password=***********;"
    },
    "dependencies": {
        "Microsoft.Extensions.Caching.Memory": "1.0.0",
        "Microsoft.AspNetCore.Session": "1.0.0"
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...