我正在与一个Mongo数据库合作,我正在尝试创建一个自定义CMS。我对MVC比较陌生,虽然对OOP语言并不陌生,而且我确实掌握了 - 我必须承认 - 依赖注入的概念,以及控制反转如何更好地胜过前者(在大多数情况下)。C#MongoDb依赖注入和控制反转
我曾试过寻找几天的互联网实例,可以通过创建我自己的DI或IoC容器来帮助我,但无济于事。从我迄今为止的理解来看,MVC(和一般的C#)在很大程度上依赖于约定,因此我的问题。
到目前为止,使用MongoDB的大学MVC项目的例子,我有这样的模式设置,可以帮助我与我的Mongo的数据库连接:
public class BlogContext
{
private static readonly MongoCredential Credentials = MongoCredential.CreateCredential("admin", "root", "*****");
private static readonly MongoServerAddress MongoServerAddress = new MongoServerAddress("localhost", 27017);
private static readonly MongoClientSettings MongoClientSettings = new MongoClientSettings
{
Credentials = new[] { Credentials },
Server = MongoServerAddress
};
public const string DATABASE_NAME = "testdb";
public const string POSTS_COLLECTION_NAME = "cmstest";
public const string USERS_COLLECTION_NAME = "users";
// This is ok... Normally, they would be put into
// an IoC container.
private static readonly IMongoClient _client;
private static readonly IMongoDatabase _database;
static BlogContext()
{
_client = new MongoClient(MongoClientSettings);
_database = _client.GetDatabase(DATABASE_NAME);
}
public IMongoClient Client => _client;
public IMongoCollection<Article> Articles => _database.GetCollection<Article>(POSTS_COLLECTION_NAME);
public IMongoCollection<User> Users => _database.GetCollection<User>(USERS_COLLECTION_NAME);
}
而且为每个控制器动作,或每当我需要访问我的数据库,我初始化BlogContext类和连接,像这样
var blogContext = new BlogContext();
await blogContext.Articles.UpdateOneAsync(x => x.Id == id, update);
我知道(我看过几次),其蒙戈使用连接池和它的线程-S AFE。我正在寻找更好的方式来实现这一点。无论是通过创建接口并使用依赖注入,还是通过使用IoC容器,就像课堂评论所暗示的那样。
我已阅读了有关通过Castle Windsor或Unity实现IoC的示例,但我在寻找的是示例。这样,也许我可以用它来创建我自己的IoC容器。
预先感谢您。
依赖注入是控制反转的一种形式,它们不是竞争性的概念 - 一个并不比另一个“更好”。 Mark Seemann的书[.NET中的依赖注入](https://www.manning.com/books/dependency-injection-in-dot-net)是一个很好的学习资源,它包含了DIY依赖注入的例子和示例使用流行的框架。 –
谢谢,我将不得不看看那本书,以便更好地理解 –