【发布时间】:2018-04-23 12:51:08
【问题描述】:
我有具有多个层的 .net core 2.0 Web API 项目,即 Presentation、BLL、DAL... 我的连接字符串位于表示层中的 appsettings.json 文件中。我的 DAL 负责根据该连接字符串从数据库中获取数据。如何读取该 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>();
}
}
【问题讨论】:
-
传递给 DAL 的连接字符串在哪里?
-
您如何创建
BaseDal的实例? -
@KirkLarkin 正确的问题来了。我正在继承 BaseDAL。查看我更新的问题
-
您在 DI 注册
MyDAL吗?如果是这样,您能否包含代码以便我提供示例解决方案?
标签: c# connection-string asp.net-core-2.0 asp.net-core-webapi