【发布时间】:2018-07-02 13:46:25
【问题描述】:
我正在使用 .Net Core 2.1 创建 Web API。我的解决方案包含不同的项目,并且在 main/startup 项目中有一个 appsettings.json 文件。 我想从不同的项目中读取 appsettings。为此,我在一个公共项目中创建了一个类,并引用了其他所有项目。
namespace Common
{
public sealed class ApplicationSettings
{
public ApplicationSettings(IConfiguration configuration)
{
InitSettings(configuration);
}
public string CloudStorageConnectionString { get; private set; }
private void InitSettings(IConfiguration configuration)
{
CloudStorageConnectionString = configuration["CloudStorageAccountConnection"];
}
}
}
然后我尝试在启动项目的Startup类中配置这个-
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//I can read the AppSettings values here via Configuration..
var settings = new ApplicationSettings(Configuration);
services.AddSingleton(settings);
}
终于用上了-
public class ToolService : IToolService
{
private DataContext _dataContext = null;
private readonly Common.ApplicationSettings _settings;
public ToolService()
{
_dataContext = new DataContext();
}
public ToolService(Common.ApplicationSettings settings)
{
_settings = settings; //settings is null here
}
public ToolDetailModel ReadToolDetail(int toolDetailID)
{
ToolDetailModel toolDetailModel = null;
try
{
var cloudConnection = _settings.CloudConnectionString; //settings is null here
//...
}
catch
{
}
return toolDetailModel;
}
}
这就是我在主启动项目中的 API 控制器中调用上述函数的方式-
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
IToolService _toolService = new ToolService();
_toolService.ReadToolDetail(1);
//...
return new string[] { "value1", "value2" };
}
}
AppSettings 对象在我尝试通过将它们作为参数传递(使用如上所示的依赖注入)在不同的项目中使用它们时为空。
我做错了吗?如果我可以添加更多详细信息,请告诉我。
【问题讨论】:
-
a different project是什么类型的项目?控制台,ASP.NET Core? -
@SimplyGed 类库项目
标签: c# asp.net-core asp.net-core-2.0 asp.net-core-webapi