service.AddScoped()vs service.AddDbContext()

时间:2017-03-10 11:01:16

标签: asp.net-core

假设我想实现不同的DbContexts(MySql,MsSql),但是让应用程序完全没有意识到它。

因此,使用“AddScoped”(或任何其他)方法,我可以注册以下内容:

<AppDbContextContract, AppDbContextMySql>
<AppDbContextContract, AppDbContextMsSql>

甚至隐藏在工厂后面的每一个。

但是使用AddDbContext()我甚至看不到一种明显的方法来实现我需要的实现而不是抽象的AppDbContextContract。

除了提供在基本应用程序中添加数据库上下文的简单方法之外,AddDbContext()方法的用途是什么?我应该更喜欢“普通”的DI方法吗?

1 个答案:

答案 0 :(得分:5)

.AddDbContext也允许您同时配置它。配置无法使用抽象类型,因为您必须将IDbContextOptionsBuilder<T>传递给DbContext,其中T是您的具体实现。

但是,如果要注入抽象类,则可以同时使用它们。

services.AddDbContext<AppDbContextMySql>( /* configure it */);
services.AddDbContext<AppDbContextSqlServer>( /* configure it */);

services.AddScoped<AppDbContextContract>(p => p.GetRequiredService<AppDbContextMySql>());
services.AddScoped<AppDbContextContract>(p => p.GetRequiredService<AppDbContextSqlServer>());

不使用.AddDbContext您需要撰写

var dbOptionsA = new DbContextOptionsBuilder<AppDbContextMySql>();
dbOptionsA.UseMySql(...);
services.AddSingleton(dbOptionsA);
var dbOptionsB = new DbContextOptionsBuilder<AppDbContextSqlServer>();
dbOptionsB.UseSqlServer(...);
services.AddSingleton(dbOptionsB);

services.AddScoped<AppDbContextContract,AppDbContextMySql>();
services.AddScoped<AppDbContextContract,AppDbContextSqlServer>();

不太好看,嗯?

但如果配置是从外部发生的,那么是的。您只能拥有一个AppDbContextContract,它接受​​IDbContextOptions<AppDbContextContract>并在库中配置它。您仍然需要在启动期间注册IDbContextOptions<AppDbContextContract>