【发布时间】:2016-06-25 23:57:44
【问题描述】:
我有一个具有以下项目结构的 ASP.NET Core 1.0 解决方案:
Web 应用程序 (ASP.NET MVC6)
BusinessLibrary(类库包)
DataLibrary(类库包)
测试(类库包 w/XUnit)
我正在尝试在整个系统中使用微软新的内置依赖注入。
这是当前所有内容从我的 ASP.NET MVC 应用程序一直流到我的存储库层的方式
//Startup.cs of MVC Web App
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton(_=> Configuration);
services.AddTransient<ICustomerService, CustomerService>();
services.AddTransient<ICustomerRepository, CustomerRepository>();
}
public class CustomersController : Controller
{
private ICustomerService _service;
public CustomersController(ICustomerService service)
{
_service= service;
}
}
public class CustomerService : ICustomerService
{
private ICustomerRepository _repository;
public PriceProtectionManager(ICustomerRepository repository)
{
_repository = repository;
}
}
public class CustomerRepository : BaseRepository, ICustomerRepository
{
public CustomerRepository(IConfigurationRoot config)
: base(config)
{
}
}
public class BaseRepository
{
private IConfigurationRoot _config;
public BaseRepository(IConfigurationRoot config)
{
_config = config;
}
}
现在我怎样才能获得与 XUnit 项目类似的东西,以便我可以访问 CustomerService 并调用函数?
这是我的 Fixture 类的样子:
public class DatabaseFixture : IDisposable
{
public ICustomerService CustomerService;
public DatabaseFixture(ICustomerService service)
{
CustomerService = service;
}
public void Dispose()
{
}
}
问题是 ICustomerService 无法解决...这可能是因为我没有像我的 WebApp 这样的 Startup.cs。如何在测试项目中复制这种行为?我不知道在哪里创建我的 TestServer,因为如果我在夹具中创建它将为时已晚。
【问题讨论】:
-
为什么不使用 ASP.NET 附带的typed options framework?这允许您只注入一个
IOptions<T>。 -
@DannyvanderKraan 请查看我对您其他帖子的评论。此外,请参阅我对当前代码的帖子所做的更新。
-
@HenkMollema 你能详细说明一下吗?请参阅我的更新帖子,了解我的 MVC 应用程序当前如何使用 DI 深入到存储库层。
-
@DannyvanderKraan 很抱歉再次打扰您,但请您看看我的编辑,看看一切如何从我的 MVC Web 应用程序流向存储库层,然后是我当前的夹具类的样子。夹具基本上相当于我的asp.net mvc应用程序中的Controller。
标签: c# asp.net asp.net-core xunit asp.net-core-1.0