將連接字符串存儲在配置文件中,在我的情況下我使用的是appsettings.json
文件。
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionString = builder["Data:DefaultConnection:ConnectionString"];
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(connectionString);
var context = new DataContext(optionsBuilder.Options);
和DataContext
類:
public class DataContext: DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
}
,你也可以通過依賴注入做。此示例我使用Autofac
:
創建ConnectionString
類:
public class ConnectionStringDto
{
public string ConnectionString { get; set; }
}
Autofac
配置:
var configBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var connectionString = new ConnectionStringDto { ConnectionString = configBuilder ["Data:DefaultConnection:ConnectionString"]; };
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterInstance(connectionStringDto).AsSelf().SingleInstance();
containerBuilder.RegisterType<DataContext>().AsSelf().InstancePerLifetimeScope();
和DataContext
類:
public class DataContext : DbContext
{
private readonly ConnectionStringDto _connectionString;
public DataContext(ConnectionStringDto connectionString)
{
_connectionString = connectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_connectionString.ConnectionString);
}
.
.
.