在ASP NET Core中注册具有原始依赖关系的类

时间:2016-11-03 09:41:02

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

一旦它被A​​SP NET Core的DI注入到mvc控制器上,我怎么能解决UserRepo上的连接字符串依赖性?请注意,我的仓库针对的是.NET 4.6。并使用sql db和dapper orm。提示和建议都可以。

继承代码。

要依赖的界面

public interface IUserRepo
{
  List<User> GetAll();
}

将注入mvc控制器并具有自己的依赖项的具体类

public class UserRepo: IUserRepo
{
   private string connectionString = "";

   //Depends on a connectionstring
   public UserRepo(string connectionString)
   {
      this.connectionString  = connectionString;
   }

   public  List<User> GetAll()
   {
      //create an sqlconnection using provided  connectionstring
      //return list from db...
   }
}

在ASP MVC CORE的startup.cs

public void ConfigureServices(IServiceCollection services)
{ 
   services.AddMvc();
   //inject UserRepo , how to resolve UserRepo's dependency?
   services.AddScoped<IUserRepo, UserRepo>();
}

2 个答案:

答案 0 :(得分:4)

您应该使用接受委托的AddScoped重载:

services.AddScoped<IAccountRepo>(c => new AccountRepo("constr"));

答案 1 :(得分:0)

我建议您使用基于ASP.NET Core文档的配置

如果你有这样的配置设置(appsettings.json):

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
}

你的Startup.cs:

private readonly IConfigurationRoot _configuration;

public Startup(IHostingEnvironment env) 
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile($"appsettings.json", optional:false, reloadOnChange:true)
        .Build(); 
}


public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<IConfiguration>(provider => _configuration);
    ...
}

然后您可以轻松地在UserRepo上解决它:

public class UserRepo: IUserRepo
{
   private readonly string connectionString;

   public UserRepo(IConfiguration configuration)
   {
      this.connectionString  = configuration.GetConnectionString("DefaultConnection");;
   }

   public  List<User> GetAll()
   {
      //create an sqlconnection using provided  connectionstring
      //return list from db...
   }
}