I'm trying to create my first webjobapp that requires the use of Entity Framework. I am trying to inject my context into the builder of the app, but I'm getting an error:
Cannot bind parameter 'db' to type ApplicationDbContext. Make sure the parameter Type is supported by the binding
There are several examples on the web but the versions of the Azure WebJob appear to have changed quickly and I can't find one that works for the version I'm using. These are the package versions I'm using:
Webjobs 3.0
EF.NET Core 7.0
Targeting .NET 7.0
Here is my code:
class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
builder.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
});
builder.ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("My full connection string"));
services.AddTransient<IEmailSender, EmailSender>();
});
var host = builder.Build();
using (host)
//{
await host.RunAsync();
}
}
}
public class Functions
public static void Sendemails([TimerTrigger("0 0 20 * * SUN-THU")] TimerInfo timer,
ILogger logger, ApplicationDbContext db)
{
var mylist = db.Users.ToList();
}
}
I tried to configure the services using the following code instead of the above code. When inspecting the builder I can see that the services were added to the builder. But inspecting the host after the call to builder.Build(), The services do not show up in the host container.
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
.....
builder.ConfigureServices((context, sc) => sc= serviceCollection);
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
.....
private void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")))
}
Project File
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.33" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings" Version="1.5.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
<PackageReference Include="SendGrid" Version="9.28.1" />
</ItemGroup>
</Project>
Initially Even I got the same error.
Done few changes in Program.cs .
My Program.cs:
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
class Program
{
static async Task Main()
{
var builder = new HostBuilder()
.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
})
.ConfigureLogging((context, b) =>
{
b.AddConsole();
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
})
.ConfigureServices(services =>
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer("MyDefaultConnection"));
services.AddTransient<ApplicationDbContext, ApplicationDbContext>();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
If you are running locally, cross check the local.settings.json file once.
My local.settings.json :
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
My appsettings.json:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "Storage Account Connection String"
}
}
Also have a look at SO Thread once.
References taken from MSDoc.
I do the steps from the beginning.
1-
public class ApplicationDbContext: IdentityDbContext<User, Role, Guid>
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
}
2-add in appsettings.json
"ConnectionStrings": {
"SqlServer": "Data Source=;Initial Catalog=SpaceManagment;User ID=sa;Password=654321;MultipleActiveResultSets=true;TrustServerCertificate=True;Connection Timeout = 60"
},
3-
add in program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options
.UseSqlServer(settings.SqlServer);
//Tips
// .ConfigureWarnings(warning => warning.Throw(RelationalEventId.QueryClientEvaluationWarning));
});
Related
I am trying to create windows service using dotnet worker project that starts up rest-api, I am using kestrel server for this purpose:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
namespace TurkisisService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
kestrelStarted=false;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
if(!kestrelStarted) {
kestrelStarted=true;
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
.Build();
var task = Task.Run(() => {
host.Run();
});
}
await Task.Delay(1000, stoppingToken);
}
}
private bool kestrelStarted;
}
public class Startup {
public void Configure(IApplicationBuilder app){
app.Run(context => {
return context.Response.WriteAsync("Hello world!");
});
}
}
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
I used these packages:
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<UserSecretsId>dotnet-turkisis_service-9216353E-18A1-49B4-8CAB-E939439FF992</UserSecretsId>
<RootNamespace>turkisis_service</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
</ItemGroup>
The console displays these lines of logs:
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
but when I open the url on web browser: http://localhost:5000, also https://localhost:5001 returns empty, they are display: ERR_EMPTY_RESPONSE
I've got asp.net core webapi app which currently uses Microsoft.AspNetCore.Identity and services.AddDbContext in ConfigureServices methods in Startup class and everything works so far.
I tried to use services.AddPooledDbContextFactory instead of services.AddDbContext to improve performance. However when I try to use AddPooledDbContextFactory I've got an error:
System.InvalidOperationException: Unable to resolve service for type
'hostapp.Data.DataContext' while attempting to activate
'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore5[hostapp.Models.AppRole,hostapp.Data.DataContext,System.Int32,hostapp.Models.AppUserRole,Microsoft.AspNetCore.Identity.IdentityRoleClaim1[System.Int32]]'
After seeing this error I created new webapi project which uses AddPooledDbContextFactory without Microsoft.AspNetCore.Identity which works fine. So my question is:
What is the proper way of using services.AddPooledDbContextFactory with Microsoft.AspNetCore.Identity to avoid error above?
in ProjectRoot/Startup.cs
using System.Threading.Tasks;
using hostapp.Data;
using hostapp.GraphQL;
using hostapp.Interfaces;
using hostapp.Models;
using hostapp.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace hostapp
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookieService, CookieService>();
// EARLIER IMPLEMENTATION WHICH WORKS FINE =>
// services.AddDbContext<DataContext>(options =>
// {
// options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
// });
// CURRENT IMPLEMENTATION WHICH CAUSES AN ERROR
services.AddPooledDbContextFactory<DataContext>(options =>
{
options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
});
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleValidator<RoleValidator<AppRole>>()
.AddEntityFrameworkStores<DataContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "app-cookie";
// options.Cookie.Expiration = TimeSpan.FromMinutes(30);
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
});
services.AddAuthorization(opt =>
{
opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<Query>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(options => options
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://localhost:4200")
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.Strict,
// HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
// Secure = CookieSecurePolicy.Always
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGraphQL();
});
}
}
}
in ProjectRoot/Data/DataContext.cs
using hostapp.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace hostapp.Data
{
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>, AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<AppUserClaim> Claims { get; set; }
public DbSet<AppUserClaimOffender> Offenders { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AppUser>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppUser)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
builder.Entity<AppRole>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppRole)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
}
}
}
in ProjectRoot/app.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0"/>
<PackageReference Include="HotChocolate.AspNetCore" Version="11.1.0"/>
<PackageReference Include="HotChocolate.AspNetCore.Authorization" Version="11.1.0"/>
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="11.1.0"/>
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0"/>
</ItemGroup>
</Project>
What is the proper way of using services.AddPooledDbContextFactory
with Microsoft.AspNetCore.Identity to avoid error above?
In the ConfigureServices, try to use AddScoped() method to register the DBContext and use the provider to get the factory from the services. Then, return the instance to the provider. The code like this:
services.AddPooledDbContextFactory<DataContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
options.EnableSensitiveDataLogging();
}, poolSize:32);
services.AddScoped<DataContext>(p => p.GetRequiredService<IDbContextFactory<DataContext>>().CreateDbContext());
I want to set all localhost port can allow CORS and then i tried to use * keyword to do it , like below code :
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
//..
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins($"http://localhost:*");
}
);
});
//..
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//..
app.UseCors(MyAllowSpecificOrigins);
//..
}
but it not work :
csproj :
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.35" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>
</Project>
I want to set all localhost port can allow CORS
To achieve above requirement, you can try:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
}
);
});
I am getting the below error :
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
Startup.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDistributedMemoryCache();
services.AddSession(options=>{options.IdleTimeout = TimeSpan.FromMinutes(1);});services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.Cookie.Name = "SampleCore";
options.LoginPath = "/log-in";
//options.AccessDeniedPath = "/access-denied";
options.LogoutPath = "/log-off";
options.ReturnUrlParameter = "postBack";
});
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
string connection = Configuration.GetConnectionString("MyConnection");
services.AddDbContext<EmployeeContext>(options => options.UseSqlServer(connection), ServiceLifetime.Scoped);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseSession();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseCustomErrorPages();
app.UseMvc();
}
UseCustomErrorPages Extension :
public async Task Invoke(HttpContext context)
{
await _next(context); // Getting error at this line
if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/page-not-found";
await _next(context);
}
else if (context.Response.StatusCode == 500)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/error";
await _next(context);
}
else if(context.Response.StatusCode == 401)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/access-denied";
await _next(context);
}
}
DbContext :
public partial class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var connectionString = "connectionString";
optionsBuilder.UseSqlServer(connectionString);
base.OnConfiguring(optionsBuilder);
}
}
public virtual DbSet<TblEmployee> TblEmployee { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Code
}
}
csproj file :
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.6" />
Controller :
private EmployeeContext _context;
public HomeController(EmployeeContext context)
{
_context = context;
}
public List<TblEmployee> GetEmployees
{
List<TblEmployee> getEmployees = _context.TblEmployee.ToList();
return getEmployees ;
}
appsettings.json :
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MyConnection": "connection string"
},
"AllowedHosts": "*"
}
I don't understand where I did wrong. Kindly help
I followed the hello world example form IOptionsSnapshot, but the content is not refreshed after file config.json is changed and saved.
My dev environment:
1.VS 2017
2 .csproj file below
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>UsingOptions</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>UsingOptions</PackageId>
<RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
<PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
</ItemGroup>
Below is the code from IOptionsSnapshot
config.json:
{
"Time": {
"Message": "Hello "
}
}
public class TimeOptions
{
// Records the time when the options are created.
public DateTime CreationTime { get; set; } = DateTime.Now;
// Bound to config. Changes to the value of "Message"
// in config.json will be reflected in this property.
public string Message { get; set; }
}
public class Controller
{
public readonly TimeOptions _options;
public Controller(IOptionsSnapshot<TimeOptions> options)
{
_options = options.Value;
}
public Task DisplayTimeAsync(HttpContext context)
{
return context.Response.WriteAsync(_options.Message + _options.CreationTime);
}
}
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
// reloadOnChange: true is required for config changes to be detected.
.AddJsonFile("config.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void Configure(IApplicationBuilder app)
{
// Simple mockup of a simple per request controller that writes
// the creation time and message of TimeOptions.
app.Run(DisplayTimeAsync);
}
public void ConfigureServices(IServiceCollection services)
{
// Simple mockup of a simple per request controller.
services.AddScoped<Controller>();
// Binds config.json to the options and setups the change tracking.
services.Configure<TimeOptions>(Configuration.GetSection("Time"));
}
public Task DisplayTimeAsync(HttpContext context)
{
context.Response.ContentType = "text/plain";
return context.RequestServices.GetRequiredService<Controller>().DisplayTimeAsync(context);
}
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
The source code of IOptions and IOptionsSnapshot look the same. Those interfaces have common implementation in OptionsManager. So OptionsSnapshot does not reload options. Instead of IOptionsSnapshot, use IOptionsMonitor. You do not need to subscribe to OnChange event, just access to CurrentValue property.
UPD
Since Microsoft.Extensions.Options 2.x release IOptionsSnapshot has been removed.