locked
How to get connection from startup to static class Data access? RRS feed

  • Question

  • User696604810 posted

    I work on asp.net core 2.2 vs2017 app I face issue I cannot get connection string from start up to static Data access class 

    class CZConnection
      public class CZConnection
        {
    
    
            public string DashboardConnection { get; set; }
    
        
        }
    StartUp.cs
    services.Configure<CZConnection>(DBConnection =>
                {
                  
                    DBConnection.DashboardConnection = Configuration.GetConnectionString("DashBoardSQLConnection");
    
    
    
                });
    
    public static partial class DataAccess
    {
      static SqlConnection InitializeConnection()
        {
         
              
                   
                    return new SqlConnection(here I need to get connection string of DBConnection.DashboardConnection);
                 
    
    
            }
            return new SqlConnection();
    
     
    }

    Wednesday, June 3, 2020 2:36 AM

All replies

  • User1120430333 posted

    The fact that you are even trying to use a static class in .NET Core is questionable. Static class causes 'static clng' that results in tightly coupled code and not clean coding.

    https://objcsharp.wordpress.com/2013/07/08/why-static-code-is-bad/

    https://docs.microsoft.com/en-us/archive/msdn-magazine/2016/may/asp-net-writing-clean-code-in-asp-net-core-with-dependency-injection

    You could look into using the info in the link. As long as you can access the appsetting.json, you don't need to have your data access class in a classlib project.

    https://corderoski.wordpress.com/2017/09/18/how-to-read-appsettings-json-from-class-library-in-asp-net-core/

    Wednesday, June 3, 2020 4:24 AM
  • User-2054057000 posted

    You can put the connection string in appsetttings.json and then do it's configuration in ConfigureServices() method of Startup.cs:

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
                services.AddMvc();
            }

    Kindly refer this tutorial for help.

    Wednesday, June 3, 2020 5:52 AM
  • User696604810 posted

    OK I need way to pass connection to class public 

    suppose I have class as below 

    public  partial class DataAccess
    {
      public SqlConnection InitializeConnection()
        {
         
              
                   
                    return new SqlConnection(here I need to get connection string of DBConnection.DashboardConnection);
                 
    
    
            }
            return new SqlConnection();
    
     
    }

    How to get connection to public class as above please ?

    Wednesday, June 3, 2020 7:00 AM
  • User-2054057000 posted

    OK I need way to pass connection to class public 

    You need to do it by injecting it to the controller through Dependency Injection. Check the tutorial link I gave you.

    Wednesday, June 3, 2020 9:02 AM
  • User-474980206 posted

    the preferred approach is to inject the configuration:

    public class DataAcessOptions
    {
       public string ConnectionString {get; set;}
       // other options
    }
    
    public  partial class DataAccess
    {
      private DataAcessOptions _options;
    
      public DataAccess(DataAcessOptions options)
      {
          _options = options;
      }
    
      public Task<SqlConnection> InitializeConnection()
      {
      }
    }
     

    also for asp.net core, you should always use async sql operations. 

    Wednesday, June 3, 2020 3:30 PM
  • User696604810 posted

    thank you for reply

    this require register as service on startup meaning must create interface for service on startup.cs or no need 

    startup.cs

    addscroped<idataaccess,dataaccess>

    or no need

    Wednesday, June 3, 2020 11:13 PM
  • User1120430333 posted

    thank you for reply

    this require register as service on startup meaning must create interface for service on startup.cs or no need 

    startup.cs

    addscroped<idataaccess,dataaccess>

    or no need

    I am getting the connectionstring and passing DI all the way through the classes to where I need the connectionstring, by using Microsoft.Extensions.Options;

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1

    I gave you the link on how to do it in my first post.

    In startup.cs Configuration service method

    //Configuration
     services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    namespace Entities
    {
        public class ConnectionStrings
        {
            public string DefaultConnection { get; set; }
            public string ProjectManagementConnection { get; set; }
        }
    }
    {
      "ConnectionStrings": {
        "DefaultConnection": "Dummy",
        "ProjectManagementConnection":
          "Server=DESKTOP-A86QNRQ\\SQLEXPRESS;Database=ProjectManagement;User Id=SA;Password=xxxxxxxxx"
      },
      "Serilog": {
        "Using": ["Serilog.Sinks.Console"],
        "MinimumLevel": "Error",
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "RollingFile",
            "Args": {
              "pathFormat": "c:\\logsapi\\log-{Date}.txt",
              "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
            }
          }
        ],
        "Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"],
        "Properties": {
          "Application": "My Application",
          "Logging": {
            "LogLevel": {
              "Default": "Warning"
            }
          },
          "AllowedHosts": "*"
        }
      }
    }
    
    using Entities;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class AppConfiguration
        {
            private readonly string _projectManagementConnection = "";
            private readonly IOptions<ConnectionStrings> _options;
    
            public AppConfiguration(IOptions<ConnectionStrings> options) 
            {
                _options = options;
                _projectManagementConnection = _options.Value.ProjectManagementConnection;
            }
    
            public string GetProjectMgmntConn() => $"{_projectManagementConnection}";
    
        }
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Transactions;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoProject :IDaoProject
        {
            private readonly IOptions<ConnectionStrings> _options;
            
            public DaoProject(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserId;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    using Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL.Models.DB
    {
        public partial class ProjectManagementContext : DbContext
        {
            private readonly IOptions<ConnectionStrings> _options;
            public ProjectManagementContext(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public ProjectManagementContext(DbContextOptions<ProjectManagementContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Projects> Projects { get; set; }
            public virtual DbSet<Tasks> Tasks { get; set; }
            public virtual DbSet<ProjectTypes> ProjectTypes { get; set; }
            public virtual DbSet<Durations> Durations { get; set; }
            public virtual DbSet<Resources> Resources { get; set; }
            public virtual DbSet<Statuses> Statuses { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlServer(new AppConfiguration(_options).GetProjectMgmntConn());
                }

    Thursday, June 4, 2020 1:39 AM