Created
July 10, 2019 18:01
-
-
Save VladislavMS/b4daeda7a4d8b1194e06c48d929ac606 to your computer and use it in GitHub Desktop.
DI 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"PhotoService": { | |
"UploadDirectory": "D:\\Uploads", | |
"PublicPath": "/Uploads" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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