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容器中 无论降低依赖关系还是调用都比较方便