如何在启动类中注册dbcontext以供参考



我在Startup中使用依赖项注入来配置我的DbContext,实际上我需要将我注册的DbContext发送到我的类处理程序(EventBusExtension.GetHandlers(((,但我不知道如何直接获取注册的上下文:

public void ConfigureServices(IServiceCollection services)
{
...
var dbContextOptions = new DbContextOptionsBuilder<cataDBContext>()
.UseSqlServer(Configuration.GetConnectionString("SqlServerConnect"))
.Options;
//*****************************************************************************
services.AddSingleton(dbContextOptions);
// Finally register the DbContextOptions:
services.AddSingleton<cataDBContextOptions>();
// This Factory is used to create the DbContext from the custom DbContextOptions:
services.AddSingleton<IContextDBFactory, ContextDBFactory>();
// Finally Add the Applications DbContext:
services.AddDbContext<cataDBContext>();
services.AddEventBusHandling(EventBusExtension.GetHandlers(Configuration));
...
}

如何获取上下文并将其发送到EventBusExtension.GetHandlers((

关于如何在启动中获取实例,可以使用以下代码:

//1.Register the service
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnnectionString")));
//2.Build an intermediate service provider
var sp = services.BuildServiceProvider();
//3.Resolve the services from the service provider
var myDbContext = sp.GetService<MyDbContext>();  
//4.then you could pass the myDbContext to the EventBusExtension.GetHandlers()

接受的anser是有效的,但正如评论和本微软文档ASP0000中所提到的,从应用程序代码调用"BuildServiceProvider"会导致创建额外的单例服务副本。调用BuildServiceProvider会创建第二个容器,该容器可以创建撕裂的singleton并导致对多个容器中的对象图的引用。

获取LoginPath的正确方法是使用选项模式对DI的内置支持。例如,使用dbContext获取所有活动的Host URL以应用于COR,而不是使用服务。AddCors(….你可以使用这个代码:

services.AddOptions<CorsOptions>()
.Configure<ApplicationDbContext>(
(options, db) =>
{
options.AddPolicy("AllowOrigin", builder =>
builder.WithOrigins(db.Set<MyHostsEntity>().Where(e => e.IsActive).Select(e => e.Url).ToArray())
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
}
);

最新更新