我在我的ASP.NET Core v2项目的Startup.cs类中有以下方法。我的问题是如何设置一个类/服务,其中传递一个字符串值到一个类,同时注入依赖项。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add custom services.
services.AddSingleton<IMyAssistantClass, MyAssistantClass);
services.AddSingleton<MyClassManager>(s => new MyClassManager("connectionString", /* How to inject IMyAssistantClass? */);
// Other setup....
}
GetRequiredService<T>
有两个原因:1.它是通用的,所以不需要转换和typeof
;2.如果找不到依赖项,它会立即失败。 - Kirk LarkinIServiceProvider
中已经有通用的扩展方法。@KirkLarkin指出了GetRequiredService<T>()
,如果无法解析,则会引发异常。还有GetService<T>()
,如果无法解析,则返回null。这些扩展方法位于Microsoft.Extensions.DependencyInjection
命名空间中。 - Brad