如何使用XUnit依赖项构造器注入创建我的具体类 [英] How to use XUnit Dependency Constructor Injection to create my concrete classes

查看:106
本文介绍了如何使用XUnit依赖项构造器注入创建我的具体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我获取xunit.DependencyInjection包,并使用接口创建了我的构造。测试用例可以编译,但是当我运行xunits时,它不会执行构造函数依赖项注入。

I nuget the xunit.DependencyInjection package and created my construction with my interfaces. The test case compiles but when I run xunits it does not execute my constructor dependency injection.

 public class TestSuite{
  IARepository _aRepository;
  IBRepository _bRepository;
    public TestSuite(IARepository aRepository, IBRepository bRepository)
    {
        _aRepository = aRepository;
        _bRepository = bRepository;
    }
}

GitHub建议可以进行构造函数注入:
https://github.com/pengweiqhca/Xunit.DependencyInjection/tree/ master / Xunit.DependencyInjection.Test

The GitHub suggests that constructor injection is possible: https://github.com/pengweiqhca/Xunit.DependencyInjection/tree/master/Xunit.DependencyInjection.Test

Startup.cs

Startup.cs

 public class Startup
 {
    public void ConfigureServices(IServiceCollection services)
    {

    var configuration = new ConfigurationBuilder()
            .SetBasePath(System.IO.Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false, true)
            .Build();

                    
        var connectionString =     configuration.GetConnectionString("A_DbCoreConnectionString");
        services.AddDbContext<AContext>(options1 => options1.UseSqlServer(connectionString));

        connectionString= configuration.GetConnectionString("B_DbCoreConnectionString");
        services.AddDbContext<BContext>(options2 => options2.UseSqlServer(connectionString));

        services.AddTransient<IARepository, ARepository>();
        services.AddTransient<IBRepository, BRepository>();
    }
  }

A和B存储库。cs

public class ARepository :IARepository
{
    public AContext _dbContext; 
    public ARepository(AContext dbContext) 
    {
        _dbContext = dbContext;
    }
    ...
}

public class BRepository :IBRepository
{
    public BContext _dbContext; 
    public BRepository(BContext dbContext) 
    {
        _dbContext = dbContext;
    }
    ...
}


推荐答案

添加了startup.cs代码后,我就能够在xunit中使用依赖项注入

I was able to get the dependency injection to work in xunit once I added the startup.cs code

这篇关于如何使用XUnit依赖项构造器注入创建我的具体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆