[.Net Core功能實現]關於MongoDB的IOC

Setting  創建文件夾MongoSetting 其中ServerSettings作爲分佈式集羣的配置信息 如果只有一個保留ServerSetting即可

{
  "ServerSettings": {
    "ReplicaSetName": "repltest",
    "IntReadPreference": 3,
    "DataBaseName": "DBAuthen",
    "serverAddresses": [
      {
        "IPAdress": "127.0.0.1",
        "Port": 27017
      },
      {
        "IPAdress": "127.0.0.1",
        "Port": 27018
      }
    ]
  },
  "ServerSetting": {
    "IPAddress": "127.0.0.1",
    "Port": 27017,
    "Account": "",
    "DataBaseName": "DBAuthen",
    "Pwd": ""
  }
}

Program中加入setting文件

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                //config.AddInMemoryCollection(arrayDict);
                config.AddJsonFile(
                    "MongoSetting.json", optional: false, reloadOnChange: false);
                config.AddCommandLine(args);
            }) .UseStartup<Startup>();

Startup 

 services.Configure<ServerSetting>(Configuration.GetSection(nameof(ServerSetting)));
            //注入MongoDbSettings對象
            services.AddScoped<AuthenContext>(sp => new AuthenContext(sp.GetRequiredService<IOptions<ServerSetting>>().Value));

Context配置

 public class AuthenContext:MongoContext
    {
        public AuthenContext(ServerSettings optionsList) :base(optionsList)
        {

        }
        public AuthenContext(ServerSetting setting) : base(setting) { 
        
        }
        public IMongoCollection<Admin> Admins { get { return base.GetMongoCollection<Admin>(); } }
       
    }

注意 context這裏直接用setting 不要用IOptions<ServerSetting> option.Value 這種形式 Startup適應去寫 不然程序會直接關閉 錯誤提示都沒有

結果 

這裏沒有使用IOC框架 所以只能以構造函數方式注入 使用框架後可以直接注入 無需構造函數

這樣做的好處是把Context注入到IOC容器中 使用起來非常方便 在Service中可以直接調用

例如

 public class AdminService:IAdminService
    {
        private AuthenContext AuthenContext { get; set; }
        public AdminService(AuthenContext authenContext)
        {
            this.AuthenContext = authenContext;
        }
}

在這裏可以直接使用 不需要去new一個Context實例

Core最重要的是降低依賴關係 這種方式所有的關係都在IOC容器中 無論降低依賴關係還是調用都比較方便

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章