-
-
Save profesor79/d837695be1500b6741b3487a6f3837a3 to your computer and use it in GitHub Desktop.
An code base changes when we switch from text file as a storage to a database. Context classes are out of scope as they are not important
This file contains hidden or 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 System.Diagnostics; | |
using Akka.Actor; | |
using Akka.Cluster.Hosting; | |
using Akka.Event; | |
using Akka.Hosting; | |
using Akka.Routing; | |
using Akka.Remote.Hosting; | |
using ASimpleApiwithActor; | |
using Microsoft.EntityFrameworkCore; | |
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Configuration | |
.AddJsonFile("appsettings.json") | |
.AddJsonFile($"appsettings.{environment}.json", optional: true) | |
.AddEnvironmentVariables(); | |
builder.Logging.ClearProviders().AddConsole(); | |
builder.Services.AddControllers(); | |
var app = builder.Build(); | |
app.UseRouting(); | |
var system = ActorSystem.Create("example"); | |
var bookActor = system.ActorOf(Props.Create(() => new BookActor()), "book"); | |
app.UseEndpoints(endpoints => { | |
endpoints.MapControllers(); | |
endpoints.MapPost("/actor", async(HttpContext context, BookData bd) => | |
{ | |
var bookId = await bookActor.Ask < ulong > (bd); | |
await context.Response.WriteAsync(bookId.ToString()); | |
}); | |
endpoints.MapPost("/class", async(HttpContext context, BookData bd) => | |
{ | |
//this is normally injected as DI in the constructory | |
var bookWriterForClass = new BookWriter(); | |
var bookId = bookWriterForClass.WriteBook(bd); | |
await context.Response.WriteAsync(bookId.ToString()); | |
}); | |
}); | |
await app.RunAsync(); | |
public class BookWriter { | |
private FirstoneContext _ctx; | |
public ulong WriteBook(BookData bd) { | |
_ctx = new FirstoneContext(); | |
var book = new Book | |
{ | |
AuthorName = bd.AuthorName, | |
Title = bd.Title | |
}; | |
_ctx.Add(book); | |
_ctx.SaveChanges(); | |
return book.Id; | |
} | |
} | |
public sealed class BookActor : ReceiveActor | |
{ | |
private readonly ILoggingAdapter _log = Context.GetLogger(); | |
private BookWriter _bookWriter = new BookWriter(); | |
public BookActor() | |
{ | |
Receive < BookData > (_ => { | |
var id = _bookWriter.WriteBook(_); | |
Sender.Tell(id); | |
}); | |
} | |
} | |
public class BookData { | |
public long Id { get; set; } | |
public string Title { get; set; } = string.Empty; | |
public string AuthorName { get; set; } = string.Empty; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment