所以我一直在关注this guide,但所有示例都是以声明它们的相同方法或在控制器中访问选项。对于我的生活,我无法弄清楚如何让它与任何随机类一起工作。
这是我目前的代码:
appsettings.json
{
"Settings": {
"GameServerVersion": 14
},
....
}
Settings.cs
public class Settings
{
public int GameServerVersion { get; set; }
}
Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();
services.AddOptions();
services.Configure<Settings>(this.Configuration.GetSection("Settings"));
JobManager.StartAsync();
}
JobManager.cs
public class JobManager
{
private static IScheduler scheduler;
public static async void StartAsync()
{
// Quartz.NET jobs
// Setup scheduler, register jobs, etc.
// Trying to retrieve ```Settings.GameServerVersion``` to pass it to one of the jobs
}
}
现在指南建议我应该使用以下内容(适用于我的示例):
private readonly Settings settings;
public JobManager(IOptions<Settings> settingsAccessor)
{
settings = settingsAccessor.Value;
}
这就是我开始迷路的地方。我知道我可以使用以下内容,但我不知道将相关参数传递给构造函数是什么或如何。
JobManager jm = new JobManager(); // cannot use an empty constructor obviously
jm.StartAsync(); // no longer a static method
我非常感谢任何帮助或指导,因为我对C#还是很陌生。
答案 0 :(得分:2)
当您使用依赖注入容器时,最好不要执行任何静态初始化(例如在您的情况下为静态RunAsync
)。相反,在容器中注册JobManager
本身(最好通过接口)(假设您通过构造函数传递IOptions
,如示例所示):
services.AddSingleton<JobManager>();
然后,稍后,例如在Configure
课程的Startup
方法中,解决它并开始:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
var jm = app.ApplicationServices.GetService<JobManager>();
jm.StartAsync();
// etc
}
如果你需要在任何控制器中使用JobManager
- 只需通过构造函数传递它 - 它将自动解决。