You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# 说明
========
EF Core 7的学习总结项目。
## 使用 工厂对象(AddDbContextFactory)时,多构建函数时, IoC获取对象时会异常
在使用扩展方法 AddDbContextFactory()注册服务时,如果 DbContext有多个构建函数, 会在获取服务时因为不知道使用哪个构建函数而异常。
解决方案:
+ 不要使用多构造函数
+ 合并成一个构建函数:比如统一使用 DbContextOptions< T > 参数, 非IoC可以手动构建 DbContextOptions< T > 对象当参数
+ 使用 ActivatorUtilitiesConstructor 特性, 指定IoC使用的构造函数
```csharp
public class AppDbContext : DbContext
{
private string? _connectString ;
public AppDbContext ()
{
}
public AppDbContext ( string? connectstring , string dd = "dd" )
{
_connectString = connectstring ;
}
//指定IoC使用的构造函数
[ActivatorUtilitiesConstructor]
public AppDbContext ( DbContextOptions < AppDbContext > options )
: base ( options )
{
}
protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder )
{
if (! optionsBuilder . IsConfigured )
{
if ( string . IsNullOrWhiteSpace ( _connectString ))
{
_connectString = @"Server=127.0.0.1\SQL2019;Database=EFCore7Study;User Id=sa;Password=xxxx;Encrypt=True;TrustServerCertificate=True;" ;
}
optionsBuilder
. UseSqlServer ( _connectString )
. EnableSensitiveDataLogging ();
}
}
protected override void OnModelCreating ( ModelBuilder modelBuilder )
{
modelBuilder . Entity < Account >(). ToTable ( "Account" );
base . OnModelCreating ( modelBuilder );
}
public DbSet < Account > Accounts { get ; set ; }
}
```