DI ConnectionString

This commit is contained in:
2025-05-19 16:05:48 +02:00
parent 8579b885e1
commit 63e516fc22
6 changed files with 40 additions and 2 deletions

View File

@@ -7,6 +7,13 @@ namespace FahrzeugeMVC.Controllers;
public class FahrzeugController : Controller public class FahrzeugController : Controller
{ {
private readonly IKonfigurationsleser _konfigurationsleser;
public FahrzeugController(IKonfigurationsleser konfigurationsleser)
{
_konfigurationsleser = konfigurationsleser;
}
public IActionResult Index(string searchTerm) public IActionResult Index(string searchTerm)
{ {
string connectionString = this.GetConnectionString(); string connectionString = this.GetConnectionString();
@@ -29,7 +36,7 @@ public class FahrzeugController : Controller
public string GetConnectionString() public string GetConnectionString()
{ {
return "Server=localhost;User ID=admin;Password=admin;Database=FahrzeugDB"; return _konfigurationsleser.LiesDBVerebindung();
} }
[HttpGet] [HttpGet]

View File

@@ -0,0 +1,6 @@
namespace FahrzeugeMVC.Models;
public interface IKonfigurationsleser
{
string LiesDBVerebindung();
}

View File

@@ -0,0 +1,16 @@
namespace FahrzeugeMVC.Models;
public class Konfigurationsleser : IKonfigurationsleser
{
private readonly IConfiguration _configuration;
public Konfigurationsleser(IConfiguration configuration)
{
this._configuration = configuration;
}
public string LiesDBVerebindung()
{
return _configuration.GetConnectionString("MariaDB");
}
}

View File

@@ -1,7 +1,10 @@
using FahrzeugeMVC.Models;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IKonfigurationsleser, Konfigurationsleser>();
var app = builder.Build(); var app = builder.Build();

View File

@@ -4,5 +4,8 @@
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
},
"ConnectionStrings": {
"MariaDB": "Server=localhost;User ID=admin;Password=admin;Database=FahrzeugDB"
} }
} }

View File

@@ -5,5 +5,8 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"ConnectionStrings": {
"MariaDB": "Server=localhost;User ID=admin;Password=admin;Database=FahrzeugDB"
}
} }