我对这种概念是陌生的,因此我对此颇为执着(解释一下我的目标是什么)。
我在rest网络api中有以下代码:
UnitOfWorkProvider.cs
public class UnitOfWorkProvider : IUnitOfWorkProvider
{
private readonly Func<AppDbContext> getDbContext;
public UnitOfWorkProvider(Func<AppDbContext> getDbContext)
{
this.getDbContext = getDbContext;
}
public IUnitOfWork Get()
{
return new AppUnitOfWork(this.getDbContext());
}
}
SimpleInjectorConfiguration.cs
internal static void Configure(this Container container, IConfigurationRoot configuration, IApplicationBuilder app, ILoggerFactory loggerFactory, IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
{
InitializeInjectorContainer(container, configuration, app, loggerFactory, httpContextAccessor, memoryCache);
}
private static void InitializeInjectorContainer(Container container, IConfigurationRoot configuration, IApplicationBuilder app, ILoggerFactory loggerFactory, IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
{
container.Register<IUnitOfWorkProvider>(() => new UnitOfWorkProvider(() => new AppDbContext(configuration.GetConnectionString("AppDbContext"))), Lifestyle.Scoped);
...
}
在Startup.cs上调用的
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
{
// Configure and register Simple Injector
simpleInjectorContainer.Configure(configuration, app, loggerFactory, httpContextAccessor, memoryCache);
...
}
我的目的是在SimpleInjectorConfiguration.cs中注册这样的IUnitOfWorkProvider:
container.Register<IUnitOfWorkProvider>();
并稍后在JWT OnTokenValidated事件上实例化它,当我从请求中的声明中获取数据库名称时:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
// get database name from claims in request
// something like this to set the context. this doesnt work.
container.GetInstance<IUnitOfWorkProvider>(() => new UnitOfWorkProvider(() => new AppDbContext(SetConnectionString(dbNameFromClaim))), Lifestyle.Scoped);
return Task.CompletedTask;
}
};
});
非常感谢谁可以帮助我! :)