gpt4 book ai didi

c# - 是否可以从另一个类库中的静态类获取 ConnectionString?

转载 作者:行者123 更新时间:2023-12-04 12:32:30 26 4
gpt4 key购买 nike

我在 appsettings.json 文件中添加了我的连接字符串。我需要访问后台操作所需的连接字符串,但为了使用连接字符串,我必须通过同一解决方案中不同项目的静态类进行访问。我无法访问使用ConfigurationManager.ConnectionStrings[""].ConnectionString .
请给我们建议,非常坚持这一点。如果有任何文件,也请发送链接。

public static class SystemConstants
{
public static string ConnectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
}

最佳答案

实际上,您可以按如下方式处理已从提供程序注入(inject) .NET Core 中的任何服务。但是你当然不能为静态类做到这一点。

public FooController(IServiceProvider serviceProvider){
var fooService = serviceProvider.GetService<IFooService>();
}
这是一个只提供服务的小 helper 。我假设服务是从另一个静态类构建的,因此我们可以获得我们需要的任何服务。
我们将扩展写入 Load()所有服务。
using Microsoft.Extensions.DependencyInjection;
using Company.Core.Utilities.IoC.DotNetCore;

namespace Company.Core.Extensions {
public static class ServiceCoreCollectionExtensions {

//You should split seperate files CoreModule and ICoreModule
public interface ICoreModule {
void Load(IServiceCollection services);
}

public class CoreModule : ICoreModule {

public void Load(IServiceCollection services) {
//Although you can add each specific service in ConfgiureService()
//you should move your Core services here, eg.
//services.AddSingleton<IAuthService, AuthService>();
}
}

public static IServiceCollection AddCoreDI(this IServiceCollection services, ICoreModule[] coreModules) {
foreach (var coreModule in coreModules) {
coreModule.Load(services);
}
return CoreServiceTool.Load(services);
}
}
}
然后我们编写一个静态类来准备服务。
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Company.Core.Utilities.IoC.DotNetCore {

public static class CoreServiceTool {

public static IServiceProvider ServiceProvider { get; private set; }

public static IServiceCollection Load(IServiceCollection services) {
ServiceProvider = services.BuildServiceProvider();

if(ServiceProvider == null) {
//I prefer to throw an exception if the developer has not implemented CoreDI()
throw new ArgumentNullException("You must call AddCoreDI() in the services");
}
return services;
}
}
}
最后,我们正在为 .NET Core 中的服务添加已经编写好的帮助程序 ConfigureService()
public void ConfigureServices(IServiceCollection services) {

services.AddCoreDI(new ICoreModule[]{
new CoreModule()
});
}
毕竟,您可以随时随地从任何层调用任何服务,例如。
static class Foo{

static Foo(){
var configuration=CoreServiceTool.ServiceProvider.GetService<IConfigurationBuilder>();
}
}

关于c# - 是否可以从另一个类库中的静态类获取 ConnectionString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67839327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com