【发布时间】:2021-03-24 14:53:23
【问题描述】:
我在应用程序上使用 hangfire,并且需要使用我的存储库进行仪表板身份验证。为此,我必须在 Hangfire 的 Authorize 方法中解析存储库,但是使用 OwinContext 我无法这样做。我选择在这个项目中使用 SimpleInjector,因为它在 WebApiConfigs Register 方法期间注册了所有内容,所以我想使用它。最近我使用了middleware 作为MessageHandler,由此,我成功地解决了使用HttpRequestMessage 的依赖关系。但是在OwinContext 上,我无法使用HttpRequestMessage.GetDependencyScope() 访问它并通过它解决依赖关系。
这就是 Hangfire 建议在其文档中对 Asp.net 应用程序进行身份验证的方式;
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
// In case you need an OWIN context, use the next line, `OwinContext` class
// is the part of the `Microsoft.Owin` package.
var owinContext = new OwinContext(context.GetOwinEnvironment());
// Allow all authenticated users to see the Dashboard (potentially dangerous).
return owinContext.Authentication.User.Identity.IsAuthenticated;
}
}
由于我在前端使用Angular,因此owinContext.Authentication.User 为空。即使不是,我也只想让自己接触到仪表板。所以这不能解决我的问题。
如何在Authorize 方法中解决我的依赖关系?
我不能通过构造函数注入来做到这一点,因为对于hangfire,您在Startup.css Configuration 上说UseHangfireDashboard,如下所示;
这是我的Startup.cs 文件
private IEnumerable<IDisposable> GetHangfireServers()
{
Hangfire.GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage("CONN_STR", new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
});
yield return new BackgroundJobServer();
}
public void Configuration(IAppBuilder app)
{
app.UseHangfireAspNet(GetHangfireServers);
app.UseHangfireDashboard("/hangfire", new DashboardOptions {
Authorization = new [] {
new DashboardAuthorization()
/* explanation */
// for DI to work through constructor,
//I have to give my AuthRepository as a parameter here.
//And my AuthRepository also has many DIs so,
//it's not possible through here.
}
});
BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
}
顺便说一下,我的项目是.Net Framework 4.7.2 项目。
【问题讨论】:
-
你尝试过构造函数注入吗?它奏效了吗?结果如何?
-
不,为了做到这一点,我必须从
Startup.cs提供它,而我似乎无法做到这一点。 -
为什么?当您无能为力时,请清楚是什么阻碍了您。
-
@mason 我编辑了问题以说明原因,谢谢您的建议 :)
-
您不需要将它们放在一个文件中。在您的 Startup.cs 中,实例化您的 DI 容器并注册您的服务。然后,您可以将该容器传递给 Web API 配置、Hangfire 配置以及您需要的任何其他地方。