【发布时间】:2021-02-22 19:57:44
【问题描述】:
我正在尝试熟悉分层解决方案中的依赖注入,该解决方案使用 .Net Core 的 MVC 和数据层按照本教程处理 MongoDB 信息:https://code-maze.com/getting-started-aspnetcore-mongodb/
我的 .sln 是这样设置的:
项目A----MVC层
项目 B ---- MongoDB 层
我要做的是使用我在视图中的 DB 层中定义的函数来显示文档的信息。我遇到的问题是弄清楚如何调用 Index .cshtml 中的函数。
按照 tut,我首先创建了一个接口来从服务中提取连接信息。由于A依赖B,所以我在B中写了这个:
namespace DataLayer
{
public class MyDBSettings : IDotNetStudyDBSettings
{
public string FileHistoryCollectioName { get; set; }
public string FileResultsCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public interface IDotNetStudyDBSettings
{
string FileHistoryCollectioName { get; set; }
string FileResultsCollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}
我在我的 Startup.cs 中配置了我的服务,以将该信息传递到此界面。根据教程,我还为我要提取的集合制作了实体模型:
public class File_History
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public DateTime Date { get; set; }
public string FileName { get; set; }
}
public class File_Result
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int Attempt { get; set; }
public string CF_Output { get; set; }
public string UR_Output { get; set; }
}
为了尝试检索集合,我在 .cshtml 中实例化了 MyDBSettings 类并将其传递给我编写的用于检索 Mongo 内容的函数:
public class MongoDB_Communicator
{
IMongoCollection<File_History> _filehistory;
public IMongoCollection<File_History> FileService(IDotNetStudyDBSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_filehistory = database.GetCollection<File_History>(settings.FileHistoryCollectioName);
return (_filehistory);
}
}
这是我最终编写的 .cshtml:
@{
DataLayer.MyDBSettings test_sets = new DataLayer.MyDBSettings();
MongoDB_Communicator test_cm = new MongoDB_Communicator();
}
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Drag Python (3) File Below. No funny business or you're out.</p>
<p>
@{
test_cm.FileService(test_sets);
}</p>
</div>
这爆炸了,给我以下错误消息:
Me being a smooth brained dork
编辑:我确实在我的 appsetting.Json 中对其进行了如下配置(已编辑以删除登录内容)
我的问题是,在实际检索信息时,我应该使用什么语法从我制作的界面中检索该设置信息?
我在我的 StartUp.cs 中进行了以下设置 - 我的印象是,通过将该类添加到服务中,一旦实例化它就会被填充。
public void ConfigureServices(IServiceCollection services)
{
//notate all of this
services.Configure<MyDBSettings>(Configuration.GetSection(nameof(MyDBSettings)));
services.AddSingleton<IDotNetStudyDBSettings>(provider => provider.GetRequiredService<IOptions<MyDBSettings>>().Value);
services.AddControllersWithViews();
services.AddControllers();
services.AddScoped<MongoDB_Communicator>();
}
我觉得这里存在概念上的差距:任何帮助将不胜感激!
【问题讨论】:
标签: c# mongodb .net-core dependency-injection asp.net-core-mvc