注入另一个服务添加ADDSQLSERVER
是否可以从configureservices
方法中解析iSettingsService
的实例?
我已经实现了一个settingsService
,该能够从外部源(安全凭据存储)检索数据库ConnectionString。在Configureservices中,我需要一个iSettingsService
的实例,以获取连接串并将其传递到services.addsqlserver< mydbContext>(connectionsTring)
method。
创建实例(使用var provider = services.buildServiceProvider(); var settings = provider.getService< isettingsProvider>()
;)Visual Studio显示下一个错误:
另一位开发人员在Stackoverflow上发布了一个类似的问题,答案在AddSingleton/addtransient的情况下提供了一个解决方案。在addsqlserver调用上应用它的正确方法是什么?还是您可以提供另一种解决方案以避免警告/错误消息?
Is it possible to resolve an instance of ISettingsService
from the ConfigureServices
method in Startup(.cs) - webapplication?
I've implemented a SettingsService
which is able to retrieve the database connectionstring from an external source (secure credentials store). Within the ConfigureServices I need an instance of the ISettingsService
in order to get the connectionstring and pass it to the services.AddSqlServer<MyDbContext>(connectionstring)
method.
While creating the instance (using var provider = services.BuildServiceProvider(); var settings = provider.GetService<ISettingsProvider>()
;) Visual Studio displays the next error:
Another developer posted a similar question on StackOverflow and the answer provides a solution in case of AddSingleton/ AddTransient. What is the correct way to apply it on the AddSqlServer call? Or could you provide another solution to avoid the warning/ error message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.addsqlServer
的Intellisense注释实际上说要使用.adddbContext
如果您需要更多的控件,这当然是正确的选项。如果您参考源代码在这里,您可以看到所有
.addsqlserver
实际上都在调用.adddbContext
并相应地配置选项。因此,我们可以这样写自己的解决方案:当然,您可以在此处对选项进行其他更改,并且
.sissqlserver
也可以采用action&lt; sqlserverdbcontextoptionsbuilder&gt;
(<代码> options.usesqlserver(connectionsTring,opts =&gt; opts.enableReTryonFailure())等)以进一步配置它。The Intellisense comment for
.AddSqlServer
actually says to use.AddDbContext
if you need more control, and that's certainly the correct option.If you refer to the source code here, you can see that all
.AddSqlServer
is actually doing is calling.AddDbContext
and configuring the options accordingly. We can therefore write our own solution like this:Of course you can make other changes to the options here, and
.UseSqlServer
can also take aAction<SqlServerDbContextOptionsBuilder>
(options.UseSqlServer(connectionString, opts => opts.EnableRetryOnFailure())
, etc.) to further configure it.