【发布时间】:2017-08-31 18:51:26
【问题描述】:
我有很多项目的解决方案:Yupii.Games -> Class Library where settings, utilities are shared with projects
Yupii.Games.Web -> Web app
Yupii.Games.Api -> Web api
我使用 mongoDB 作为数据库,我有很多集合,但我想尊重集合名称约定,例如:
Monster(是一个实体)到 monsters集合名称。
我在 Yupii.Games 中有一个名为 GlobalSettings.json 的 json 文件:
"MongoDBCollections": {
"Collections": [
{ "Monster": "monsters" },
{ "User": "users" }
...
]}
在 Yupii.Games.Api 我有类似的东西:
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();
services.Configure<MongoDbSettings>(options =>
{
options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoConnection:Database").Value;
)};
}
我怎样才能到达 GlobalSettings.json -> "MongoDBCollections" -> Collections[] 也有一个服务:
services.Configure<GlobalSettings>(options =>
{
options.Collections = CollectionsConfiguration.GetSection("MongoDBItems:Collections").Get<Dictionary<string, string>>();
});
然后循环获取关联集合名称:
var collectionName = typeof(T).Name;
foreach (var collection in CollectionList)
{
if (collectionName == collection.Key)
return Database.GetCollection<T>(collection.Value);
}
return Database.GetCollection<T>(collectionName);
我希望能够在 Yupii.Games.Web 中做同样的事情
实际上,我可以让每一个都以不同的方式正常工作,但代码和结构很糟糕。如果有任何机构可以表现出更好更干净的方式,请。
我正在使用 Visual Studio 2017 asp.net core 2.0
我希望一切都清楚...
更新
在 Yupii.Games.Web 中,其中一种方法是这样调用的:
HttpResponseMessage response = client.GetAsync(RESTVersion + GetCollectionName() + e).Result;
和 GetCollectionName():
public string GetCollectionName()
{
string collectionName = typeof(T).Name;
... // get the collection name by associating the typeof(T)
return name;
}
【问题讨论】:
-
只是好奇 - 为什么使用 GlobalSetting.json 而不是应用程序为您读取的
appSetting.json?我还假设 web 将是您的启动项目 - 为什么不将文件放在那里,因为您的startup.cs驻留在 web 或 api 中 -
因此,如果我将 MongoDBCollections 放置在 Yupii.Games.Api appSettings.json 中,我如何从 Yupii.Games.Web 访问它?我不想在 appSettings.json(Web 和 Api)中重复 MongoDBCollection json 元素。我也有使用 HttpClient 进行调用的 Xamarin。
-
哪个项目需要它?我认为这是网络 api 对吗? - 然后将其放在该项目中,并在 startup.cs 上读取文件并遍历集合,我假设您的网络正在使用 api
-
肯定是 Api,其他的都有一个通用的类库 Yupii.Games.WebHTTP 来进行 Http 调用。 (我更新了我的问题)。所以 Web 和 Xamarin 有一个 Yupii.Games.WebHTTP 引用来使用 RESTful api。
-
再次,如果 web api 有它需要的一切并且客户端只是调用它,我不明白为什么它应该在 web 或 Xamarin 中?
标签: c# json mongodb asp.net-core-2.0 asp.net-core-mvc-2.0