【发布时间】:2021-12-28 20:10:21
【问题描述】:
我目前正在尝试找到一种更好的方法来调用另一个类服务的构造函数中的服务函数。我对自己正在做的事情有一种不好的感觉,并认为我正在与 ASP .Net Core 的基础作斗争。我的问题是,我是否与.Net 方式作斗争?有没有更好的方法让我不创建 CryptionService 的新实例?
//this singleton has a function called GetSQLitePassword that returns a string
services.AddSingleton<ICryptionService, CryptionService>();
// Use value returned from cryptionService
services.AddScoped<ISQLiteSettingsRepo,
SQLiteSettingsRepo>(x => new SQLiteSettingsRepo(
"./Settings.db",
new CryptionService().GetSQLitePassword()
));
我想我可以做这样的事情:
services.AddScoped<ISQLiteSettingsRepo, SQLiteSettingsRepo>(x => new SQLiteSettingsRepo(
"./Settings.db",
service.GetService<ICryptionService>().GetSQLitePassword()
));
【问题讨论】: