繁体   English   中英

C#MongoDb依赖注入和控制反转

[英]C# MongoDb Dependency Injection & Inversion of Control

我正在使用Mongo数据库创建我要创建的自定义CMS。 我对MVC相对较新,尽管并不熟悉OOP语言,但是我确实抓住了-隐约承认-依赖注入的概念,以及控制反转如何更好地使前者超越(在大多数情况下)。

我尝试在Internet上寻找几天的示例,这些示例可以通过创建自己的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);

我确实知道(而且我读过几次),Mongo使用了一个连接池,并且它是线程安全的。 我正在寻找一种更好的方法来实现这一目标。 通过创建接口并使用依赖注入,或者使用IoC容器(如类注释所建议的那样)。

我已经阅读了有关通过Castle Windsor或Unity实现IoC的信息,但是我想要的只是一个示例 这样,也许我可以使用它来创建自己的IoC容器。

先感谢您。

这是使用ServiceStack.Funq的示例

您的global.asax应该看起来像这样

    protected void Application_Start()
    {
        Funq container = new Funq.Container();

        container.Register<IMyType>(c => new MyType());
        ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
    }

和你的控制器

public class ExampleController : ServiceStackController
{
   public IMyType MyType {get;set;}

   public ActionResult Index(){
      return View();
   }
}

MyType将由IoC容器自动接线。

有很多成熟的IoC容器具有广泛的MVC支持,因此无需实现自己的容器。 您可以研究性能功能基准,选择一些顶级产品,然后在文档中寻找MVC集成。 通常包括示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM