簡體   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