如何在ASP.NET Core v2中传递字符串以及注入的依赖项

时间:2018-06-13 07:20:39

标签: asp.net asp.net-core dependency-injection .net-core

我的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....
    }

2 个答案:

答案 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"));