使用 .NET Core 2.1、NPGSQL、实体框架和 Linux。
从 Startups.cs 的 Configure 函数中,我在依赖注入类中调用一个函数,该类又调用另一个依赖注入类,该类使用 Entity Framework + NPGSQL 访问数据库。
配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkNpgsql()
.AddDbContext<MMContext>(options => options.UseNpgsql($"Host='localhost'; Port=1234;Database='mydb';Username='test';Password='test'"))
.BuildServiceProvider();
services.AddTransient<IMusicManager, MusicManager>();
services.AddTransient<IMusicRepo, MusicRepo>();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
配置功能:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var mm = scope.ServiceProvider.GetRequiredService<IMusicManager>();
mm.DoSomeDBStartupStuff();
}
}
音乐管理器
实现看起来像这样:
private readonly IMusicRepo _musicStoreRepo;
public MusicManager(IMusicRepo musicStoreRep)
{
_musicStoreRepo = musicStoreRepo;
}
public void DoSomeDBStartupStuff()
{
_musicStoreRepo.InsertSampleStuff();
_musicStoreRepo.CheckThisAndCheckThat();
}
音乐库
实现看起来像这样:
private readonly MMContext _context;
public MusicRepo(MMContext context)
{
_context = context;
}
public void InsertSampleStuff()
{
_context.Music.AddAsync(new music("abc"));
_context.Music.AddAsync(new music("123"));
_context.SaveChangesAsync();
}
MM上下文
这是这样实现的:
public class MMContext : DbContext
{
public MMContext(DbContextOptions<MMContext> options) : base(options) {}
... OnModelCreating etc...
}
眼眸繁星
相关分类