我正在读一本书,对存储库感到困惑,下面是代码:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { }
public DbSet<Product> Products { get; set; }
}
public class EFProductRepository : IProductRepository
{
private ApplicationDbContext context;
public EFProductRepository(ApplicationDbContext ctx)
{
context = ctx;
}
public IQueryable<Product> Products => context.Products;
}
和startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:SportStoreProducts:ConnectionString"]));
services.AddTransient<IProductRepository, EFProductRepository>();
}
所以我的问题是:
我知道Q {1}存储库服务,因此当应用程序的其他部分需要services.AddTransient<IProductRepository, EFProductRepository>();
时,将给出一个新的IProductRepository
对象。但是,EFProductRepository的构造函数需要一个EFProductRepository
对象ctx呢,我们是否不需要编写与以下代码相同的代码:
ApplicationDbContext
或services.AddTransient<ApplicationDbContext, ...>();
与services.AddDbContext
Q2-ApplicationDbContext还具有一个需要services.AddTransient<ApplicationDbContext, ...>();
对象选项的构造函数,那么如何注册该选项?
答案 0 :(得分:1)
通过检查以下行可以回答您的两个问题:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:SportStoreProducts:ConnectionString"]));
这会将您的ApplicationDbContext
注册为依赖项解析器的临时对象。这部分:
options => options.UseSqlServer(Configuration["Data:SportStoreProducts:ConnectionString"])
正在创建DbContext的构造函数所需的DbContextOptions
对象。因此,它不是“技术上”注册为可解析类型的,而是整行代码让应用程序知道如何在请求时创建ApplicationDbContext
。