在AddDbContext之后,现在我想使用我的上下文

时间:2019-05-08 18:33:52

标签: entity-framework-core

我决定使用此AddDbContext方法为Entity Framework Core项目添加和设置上下文。

services.AddDbContext<ExampleContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ExampleConnection"))); 
// https://stackoverflow.com/a/51970589/196526

我想这个AddDbContext允许我们添加一个全局上下文,并且有可能以后在我的控制器或服务类中需要时可以检索它。我该怎么用?

1 个答案:

答案 0 :(得分:0)

好吧,dotnet核心现在内置了依赖项注入。在控制器,服务或存储库类中使用它的方式就像通过构造函数注入一样简单。

示例-

public class AccountRepository : IAccountRepository{
   private readonly DbContext _exampleContext;
 public AccountRepository(ExampleContext context){
   _exampleContext = context;
}

}