我的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....
}
答案 0 :(得分:3)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyAssistantClass, MyAssistantClass);
services.AddSingleton<MyClassManager>(s =>
{
var imy = (IMyAssistantClass) s.GetService(typeof(IMyAssistantClass))
new MyClassManager("connectionString", imy);
}
);
}
//使其更方便的好方法是将扩展方法添加到IServiceCollection
,例如
public static T Resolve<T>(this IServiceProvider serviceProvider)
{
return (T) serviceProvider.GetService(typeof(T));
}
然后你可以拨打s.Resolve<IMyAssistantClass>();
答案 1 :(得分:1)
将connectionString
变量提升为参数对象,并在容器中注册该对象:
public class MyClassManagerSettings
{
public readonly string ConnectionString;
public MyClassManagerSettings(string connectionString) {
this.ConnectionString = connectionString
?? throw new ArgumentNullException(nameof(connectionString));
}
}
public class MyClassManager
{
public MyClassManager(
MyClassManagerSettings settings, IMyAssistantClass assistant)
{
...
}
}
您可以按如下方式注册:
services.AddSingleton<IMyAssistantClass, MyAssistantClass);
services.AddSingleton<MyClassManager>();
services.AddSingleton(new MyClassManagerSettings("myConnectionString"));