fix lazy loading

This commit is contained in:
mkbka 2024-06-02 11:31:17 +08:00
parent 7669e64f9a
commit a82e9a6b50
3 changed files with 39 additions and 33 deletions

View File

@ -1,20 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace SCHALE.Common.Database
{
public static class ServicesExtesions
{
public static void AddSQLServerProvider(this IServiceCollection services, string connectionString)
{
services.AddDbContext<SCHALEContext>(o =>
{
o.UseSqlServer(connectionString, b =>
{
b.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
})
.UseLazyLoadingProxies();
}, ServiceLifetime.Singleton, ServiceLifetime.Singleton);
}
}
}

View File

@ -80,19 +80,8 @@ namespace SCHALE.GameServer
);
builder.Host.UseSerilog();
// Add services to the container.
builder.Services.AddSingleton<SCHALEContext>(s =>
{
var sqlProvider = config.GetValue<string>("SQL Provider");
var noConnectionStringException = new ArgumentNullException($"ConnectionString for {sqlProvider} in appsettings is missing");
return sqlProvider switch
{
"SQLite3" => SCHALESqliteContext.Create(config.GetConnectionString("SQLite3") ?? throw noConnectionStringException),
"SQLServer" => SCHALEContext.Create(config.GetConnectionString("SQLServer") ?? throw noConnectionStringException),
_ => throw new ArgumentException($"SQL Provider '{sqlProvider}' is not valid"),
};
});
// Add services to the container.
builder.Services.AddDbProvider(config);
builder.Services.AddControllers();
builder.Services.AddProtocolHandlerFactory();
builder.Services.AddMemorySessionKeyService();

View File

@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore;
using SCHALE.Common.Database;
namespace SCHALE.GameServer.Utils
{
public static class ServicesExtesions
{
public static Exception NoConnectionStringException = new ArgumentNullException($"ConnectionString in appsettings is missing");
public static void AddDbProvider(this IServiceCollection services, IConfiguration conf)
{
var sqlProvider = conf.GetValue<string>("SQL Provider");
switch (sqlProvider)
{
case "SQLite3":
services.AddDbContext<SCHALEContext, SCHALESqliteContext>(opt =>
opt
.UseSqlite(conf.GetConnectionString("SQLite3") ?? throw NoConnectionStringException)
.UseLazyLoadingProxies()
, ServiceLifetime.Singleton, ServiceLifetime.Singleton);
break;
case "SQLServer":
services.AddDbContext<SCHALEContext>(opt =>
opt
.UseSqlServer(conf.GetConnectionString("SQLServer") ?? throw NoConnectionStringException,
actions =>
{
actions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
})
.UseLazyLoadingProxies()
, ServiceLifetime.Singleton, ServiceLifetime.Singleton);
break;
default: throw new ArgumentException($"SQL Provider '{sqlProvider}' is not valid");
}
}
}
}