Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DI 2
{
"PhotoService": {
"UploadDirectory": "D:\\Uploads",
"PublicPath": "/Uploads"
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace DiExamples
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<PhotoServiceOptions>(Configuration.GetSection("PhotoService"));
services.AddSingleton<IPhotoService, PhotoService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
var photoService = context.RequestServices.GetRequiredService<IPhotoService>();
await context.Response.WriteAsync(photoService.Upload());
});
}
}
public interface IPhotoService
{
string Upload();
}
public class PhotoServiceOptions
{
public string UploadDirectory { get; set; }
public string PublicPath { get; set; }
}
public class PhotoService : IPhotoService
{
private readonly PhotoServiceOptions _options;
public PhotoService(IOptionsMonitor<PhotoServiceOptions> serviceOptions)
{
_options = serviceOptions.CurrentValue;
}
public string Upload()
{
// Do some work
return $"Upload Done. Folder {_options.UploadDirectory} , Path {_options.PublicPath}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.