pun*_*ter 4 c# entity-framework dependency-injection entity-framework-core asp.net-core
我遵循了将 EF Core 与 ASP.NET Core 一起使用的模式,一切都很好。但最近我创建了一个“计算”项目,并希望从中进行数据库调用。
问题是我不知道如何创建一个新的DbContextOptions. 在我完成的代码中
services.AddDbContext<RetContext>(options => options
.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Run Code Online (Sandbox Code Playgroud)
但是在新的 .NET 核心类中,我需要手动提供它。我该怎么做呢 ?我的代码是这样的:
public static class LoadData
{
public static IConfiguration Configuration { get; }
public static RefProgramProfileData Load_RefProgramProfileData(string code)
{
// var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
// optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
//How do I make an optionsbuilder and get the configuration from the WEB project?
UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder));
var loadedRefProgramProfileData = uow.RefProgramProfileDataRepository
.Find(x => x.ProgramCode == code).FirstOrDefault();
return loadedRefProgramProfileData;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以DbContext像这样实例化你:
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
var configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
optionsBuilder.UseSqlServer(configuration.GetConnection("DefaultConnection"));
_context = new RetContext(optionsBuilder.Options);
Run Code Online (Sandbox Code Playgroud)
然而,理想的是使用依赖注入。假设您CalculationService在其他项目中有一个课程。为此,您需要将该类注册为可以注入的服务:
services.AddScoped<CalculationService>();
Run Code Online (Sandbox Code Playgroud)
然后您的班级可以DbContext通过 DI接收(或任何其他服务):
public class CalculationService
{
private RetContext _context;
public CalculationService(RetContext context)
{
_context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您将无法像这样手动实例化您的类:
var service = new CalculationService();
Run Code Online (Sandbox Code Playgroud)
相反,您需要让任何需要使用的类CalculationService也通过 DI 接收它并使该类也可注入。
| 归档时间: |
|
| 查看次数: |
2642 次 |
| 最近记录: |