如何从表示层

时间:2018-04-23 12:51:08

标签: c# connection-string asp.net-core-2.0 asp.net-core-webapi

我有.net core 2.0 Web API项目,有多个层,即Presentation,BLL,DAL ...我在appsettings.json文件中有我的连接字符串,它存在于Presentation层中。我的DAL负责根据该连接字符串从DB获取数据。如何读取该json文件或将连接字符串传递给DAL。
附:表示层依赖于BLL,BLL依赖于DAL。

  

appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionStrings": {
    "MsSqlConnectionString": "Data Source=myServerName;Database=myDB;User Id=myUserID;Password=myPWd;"
  }
}


  

DAL课程

protected readonly string _connectionString;
protected IDbConnection _connection { get { return new SqlConnection(_connectionString); } }

public BaseDal()
{
    _connectionString = "<<How to get connectionstring from appsetting.json>>";
}


  

ChildDAL

public class MyDAL : BaseDal, IMyDAL
{
    ILogger _log;
    public MyDAL(ILoggerFactory loggerFactory)
    {
        _log = loggerFactory.CreateLogger("ChildDAL");
    }
    public async Task<IEnumerable<MyModel>> MyMethod(Dto criteria)
    {
        StringBuilder sql = new StringBuilder();

        sql.Append("SELECT * FROM table");
        string query = sql.ToString();
        // custom mapping
        DapperCustomMapping<MyModel>();

        using (IDbConnection dbConnection = _connection)
        {
            return await dbConnection.QueryAsync<MyModel>(query);
        }
    }
}
  

Startup.cs

public class Startup
{
    public IConfigurationRoot Configuration { get; }

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

        Configuration = builder.Build();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        loggerFactory.AddLog4Net();

        app.UseErrorWrappingMiddleware();
        app.UseStatusCodePagesWithReExecute("/error/{0}");
        app.UseExceptionHandler("/error/500");

        // CORS: UseCors with CorsPolicyBuilder.
        app.UseCors("AllowSpecificOrigin");

        // MVC
        app.UseMvc();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        //Enable middleware to serve swagger - ui
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("../swagger/v1/swagger.json", "My API v1");
        });
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Read appsettings.json to get allowed origins
        var whiteList = new List<string>();
        var myArraySection = Configuration["AllowedOrigin"];
        if (!String.IsNullOrEmpty(myArraySection))
        {
            foreach (var d in myArraySection.Split(','))
            {
                whiteList.Add(d.Trim());
            }
        }

        // CORS
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                policy => policy.WithOrigins(whiteList.ToArray()));
        });

        // Add framework services.
        services.AddMvc(options =>
        {
            // install global fitler on all controllers and actions.
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            options.Filters.Add(new ValidateModelAttribute());
        })
        // tell how to find the fluent validations
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ContactQueryDtoValidator>());

        // Register the Swagger generator
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" });
        });

        return ConfigureIoC(services);
    }

    public IServiceProvider ConfigureIoC(IServiceCollection services)
    {
        var container = new Container();
        container.Configure(config =>
        {
            config.Scan(_ =>
            {
                _.AssemblyContainingType(typeof(Startup)); // web api
                _.AssemblyContainingType(typeof(HelloBLL)); // Unused BLL
                _.AssemblyContainingType(typeof(HelloDAL)); // Unused DAL
                _.TheCallingAssembly();
                _.WithDefaultConventions();

            });

            config.Populate(services);
        });
        return container.GetInstance<IServiceProvider>();
    }
}

2 个答案:

答案 0 :(得分:0)

访问配置文件的另一种方法,引自https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration

确保导入以下库

using Microsoft.Extensions.Configuration;
using System.IO;

    public BaseDal()
    {
        var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        var _connectionString = Configuration.GetConnectionString("CONNECTION_STRING")
    }

答案 1 :(得分:0)

假设您已在表示层的startup.cs文件中注册了该部分。

  public class AppSettings
    {
        public string MsSqlConnectionString{ get; set; }
    }

   //registering in ConfigureServices method of Startup.cs
   services.Configure<AppSettings>(Configuration.GetSection("ConnectionStrings"));

要在DAL层中进行模拟访问,您还必须在那里创建AppSettings类,然后只需使用

public BaseDal(IOptions<AppSettings> app)
{
    _connectionString = app.Value.MsSqlConnectionString;;
}

修改

收到

  

错误:没有给出符合要求的参数   'BaseDal.BaseDal(IOptions)'

的形式参数'app'

这意味着你没有给它所需的参数。您可以通过调用required构造函数来调用基类并提供:base(parameters...)参数。

public class MyDAL : BaseDal, IMyDAL
{
    ILogger _log;
    public MyDAL(ILoggerFactory loggerFactory,IOptions<AppSettings> app):base(app)
    {
        _log = loggerFactory.CreateLogger("ChildDAL");
    }
}