ASP.NET Core 101 - Adding a Service to an ASP.NET Core Website [4 of 13]
JsonFileProductService
what we're going to do is we're going to add a service,
So in this context,service is like if you're at a restaurant and the waiter asks you what you want and you can request.
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using ContosoCrafts.WebSite.Models; using Microsoft.AspNetCore.Hosting; namespace ContosoCrafts.WebSite.Services { public class JsonFileProductService { public JsonFileProductService(IWebHostEnvironment webHostEnvironment) { WebHostEnvironment = webHostEnvironment; } public IWebHostEnvironment WebHostEnvironment { get; } private string JsonFileName { get { return Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json"); } } public IEnumerable<Product> GetProducts() { using(var jsonFileReader = File.OpenText(JsonFileName)) { return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } } }
When you're in Visual Studio,it is a text editor. It's like Notepad but it's a smart text editor.So that means it can probably identify what the functions are that we just made.
but also the Smart Text Editorwill allow me to collapse.(Ctrl+M+O)
So let's see what's going on here.We have a thing called JsonFileProductService. This is our constructor.
Well, web applications are hosted, they live in a host.They're actually Console apps.Do you know that an ASP.NET app is a Console app as well?
program.cs
So if you go to program.cs,there is a main except it's not a main that says console.writeline,it's a main that makes the host.
namespace ContosoCrafts.WebSite { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
Json File Path
we can let this WebHostEnvironment know the path where this file comes from.we have wwwroot, data, products.I don't want to hard code that C:\\.
But what we did is we said, "Hey,WebHostEnvironment,where is the web root?" Your disk and my disk and their disk is different.
We're going to use an another library called System.IO.Path.
private string JsonFileName { get { return Path.Combine(WebHostEnvironment.WebRootPath, "data", "products.json"); } }
We're going to combine three parts.So the first one is wwwroot,the next one is data,and you can combine as many passes as you want and they're taking care of the slashes(斜杆) and the backslashes(反斜杆) and this and that.
deserializing
we have to convert that text into the actual product that we defined back in the last video.So to do that, we talked before about serializing.In this case, we're de-serializing. So we're taking that JSON text and converting it into the object that we created.
public IEnumerable<Product> GetProducts() { using(var jsonFileReader = File.OpenText(JsonFileName)) { return JsonSerializer.Deserialize<Product[]>(jsonFileReader.ReadToEnd(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true //( 未意识到的,漠不关心的; ) }); } }
we're going to de-serialize and this is interesting,we're making an array of products,not one product but products.We're going to read that JSON file to the end.
Here, we can pass in some optional options and these are not required, they are optional.We're saying don't really care about uppercase lowercase, just make it work.
IEnumerable
Then, this is interesting and IEnumerable, I was using lists. Me too I typically(通常; 一般;) use lists.IEnumerable is the great great grandparent(祖父; 祖母;) of lists.
It's stuff that you can for each over, that's how I think about it.we talked about 'for' loops and 'for eaches',things that you can 'for' each over are things that you can enumerate.
How do we publicize it?
We have a waiter now, tell everyone in the restaurant there's a waiter.We need to make sure that ASP.NET knows that this is an available service.
In startup, this is a special ASP.NET page.What it is is it's a special file that has a couple of methods that we want to care about and the methods are Configure and ConfigureServices.
So remember how you said that we were going to make a JsonFileProduct as a service? So what we want to do is we want to go into ConfigureServices and we're going to tell it about this new service.
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddHttpClient(); services.AddControllers(); services.AddTransient<JsonFileProductService>(); }
There's two major ones,singleton which is, just make it so there's only one of these surfaces.Then transient(短暂的; 临时的;), a transient is a thing that comes and goes.
So now, the service that we just made Is a member of this collection of services and it's a Transient service,