twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

AspNet Core 6 F# 依赖注入 #389

Open twn39 opened 2 years ago

twn39 commented 2 years ago

.Net 6 简化了 Aspnet 模版:

namespace WebApplication1
#nowarn "20"
open Serilog
open StackExchange.Redis
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.Hosting
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.DependencyInjection

module Program =
    let exitCode = 0

    [<EntryPoint>]
    let main args =

        let builder = WebApplication.CreateBuilder(args)

        let loggerConfig = LoggerConfiguration()
        let logger = loggerConfig.WriteTo.Console().CreateLogger()

        let appConfig = builder.Configuration
        let host = appConfig["Redis:Host"]
        let port = appConfig["Redis:Port"]
        use redisClient = ConnectionMultiplexer.Connect(sprintf $"{host}:{port}")
        let db = redisClient.GetDatabase(0)

        builder.Services.AddControllers()
        builder.Services.AddSingleton<IDatabase>(fun sp -> db)
        builder.Services.AddScoped<ILogger>(fun sp -> logger)

        let app = builder.Build()

        use serviceScope = app.Services.CreateScope() in
            let services = serviceScope.ServiceProvider
            let logger = services.GetRequiredService<ILogger>()
            let env = services.GetRequiredService<IWebHostEnvironment>()
            logger.Information($"{env.ContentRootPath};{env.WebRootPath}")

        app.UseHttpsRedirection()
        app.UseAuthorization()
        app.MapControllers()
        app.UseStaticFiles()

        app.Run()

        exitCode

appsettings.Development.json 配置文件:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Redis": {
    "Host": "localhost",
    "Port": 6379
  }
}

HomeController.cs 中注入依赖:

namespace WebApplication1.Controllers

open Serilog
open Microsoft.AspNetCore.Mvc
open StackExchange.Redis

type ResData<'T> = {
    Code: int
    Data: 'T
    Msg: string
}

[<ApiController>]
[<Route("/")>]
type HomeController (logger : ILogger, redisDB: IDatabase) =
    inherit ControllerBase()

    [<HttpGet>]
    [<Produces("application/json")>]
    member _.Get() = task {
        redisDB.StringSet("name", "Hello F#, aspnet core.") |> ignore
        let data = redisDB.StringGet("name")
        logger.Information($"Data: {data}")
        let data = {
            Code = 0
            Data = Map.empty
            Msg = "ok"
        }
        return OkObjectResult(data)
    }