【发布时间】:2018-10-23 23:10:24
【问题描述】:
我使用的是 .net core 2.0,我的结构基本上是这样的:我有 20 个 Web Api 项目和一个类库 (DbContext) 项目。 Web Api 项目有Startup.cs。但是类库没有Startup.cs。我应该在哪里写连接字符串?因为类库没有app.config 或Startup.cs。如果我写 API 的Startup.cs,那么我必须写 connectionString 20 次。这是不可接受的。我使用DbContextOptions 编写如下,但我不确定,这是最好的方法。最好的方法是什么?
public class MyDbContext : DbContext
{
private readonly IAuditHelper auditHelper;
public MyDbContext(DbContextOptions<MyDbContext> options, IAuditHelper auditHelper)
: base(GetOptions())
{
this.auditHelper = auditHelper;
}
private static DbContextOptions GetOptions()
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "server=asdf; database=asdf; user id=asdf; password=asdf").Options;
}
public async Task<int> SaveChangesWithoutAuditAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return (await base.SaveChangesAsync(true, cancellationToken));
}
}
【问题讨论】:
-
没有 app.config 但 app.json :-) docs.microsoft.com/en-us/ef/core/miscellaneous/…
-
感谢您的回复@LaurentLequenne。我想学习的主要是使用 DbContextOptions 是最好的方法还是有更好的方法?
-
如果这是一个类库,您应该通过依赖注入方式将配置的注入留给库的使用者,而不是将其作为一个实施细节
-
非常感谢您的回答和建议@MartinCostello
标签: c# asp.net-core asp.net-core-webapi