C# IHostingEnvironment用于测试

C# IHostingEnvironment用于测试,c#,aspnetboilerplate,C#,Aspnetboilerplate,我试图在ABP2.0.2中使用单元测试项目,当我运行所选测试GetUsers\u test()时,出现以下错误 Message: Castle.MicroKernel.Handlers.HandlerException : Can't create component 'imfundoplatform.imfundoplatformCoreModule' as it has dependencies to be satisfied. 'imfundoplatform.imfundoplatfo

我试图在ABP2.0.2中使用单元测试项目,当我运行所选测试GetUsers\u test()时,出现以下错误

Message: Castle.MicroKernel.Handlers.HandlerException : Can't create component 'imfundoplatform.imfundoplatformCoreModule' as it has dependencies to be satisfied.

'imfundoplatform.imfundoplatformCoreModule' is waiting for the following dependencies:
- Service 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' which was not registered.
我的核心模块的构造函数:

public imfundoplatformCoreModule(IHostingEnvironment env)
{
    _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
}
我不知道如何将其传递给模块或使单元测试正常工作。请帮忙

您不能将IHostingEnvironment。。。要获取内容根路径,请使用

Directory.GetCurrentDirectory
您不能将IHostingEnvironment。。。要获取内容根路径,请使用

Directory.GetCurrentDirectory
您可以将IHostingEnvironment注入。但你必须用一些奇怪的方式来做:

首先创建一个类似这样的模拟iHostingVrioment类(根据需要进行调整):

之后,将其添加到TestModule的
Initialize()

public override void Initialize()
{
    (...)
    IocManager.Register<IHostingEnvironment, MockHostingEnvironment>(DependencyLifeStyle.Singleton);
}
public override void Initialize()
{
(...)
IocManager.Register(DependencyLifeStyle.Singleton);
}
请注意,使用Environment.CurrentDirectory是一种非常糟糕的方法。它可能指向不同的目录,具体取决于您的CI、测试运行程序、测试框架等

只有在测试中使用需要IHostingEnvironment的服务时,才应使用此MockHostingEnvironment。

您可以注入IHostingEnvironment。但你必须用一些奇怪的方式来做:

首先创建一个类似这样的模拟iHostingVrioment类(根据需要进行调整):

之后,将其添加到TestModule的
Initialize()

public override void Initialize()
{
    (...)
    IocManager.Register<IHostingEnvironment, MockHostingEnvironment>(DependencyLifeStyle.Singleton);
}
public override void Initialize()
{
(...)
IocManager.Register(DependencyLifeStyle.Singleton);
}
请注意,使用Environment.CurrentDirectory是一种非常糟糕的方法。它可能指向不同的目录,具体取决于您的CI、测试运行程序、测试框架等


只有在测试中使用需要IHostingEnvironment的服务时,才应该使用此MockHostingEnvironment。

但是我仍然需要从模板创建的构造函数中删除IHostingEnvironment。我的核心模块还能工作吗?源代码中没有IHostingEnvironment。请参阅源代码,如果要测试依赖IHostingEnvironment的AppServices,这将没有帮助。另一种解决方案是模拟IHostingEnvironment。您的设计肯定有问题。AppServices是应用程序逻辑代码,不属于Web层。因此,如果需要某个根路径,则必须将其作为运行平台的参数发送。(例如:如果您正在使用来自Xamarin平台的AppServices,因此HostingEnvironment没有意义),但是我仍然需要从模板创建的构造函数中删除IHostingEnvironment。我的核心模块还能工作吗?源代码中没有IHostingEnvironment。请参阅源代码,如果要测试依赖IHostingEnvironment的AppServices,这将没有帮助。另一种解决方案是模拟IHostingEnvironment。您的设计肯定有问题。AppServices是应用程序逻辑代码,不属于Web层。因此,如果需要某个根路径,则必须将其作为运行平台的参数发送。(例如:如果您正在使用来自Xamarin平台的AppServices,因此HostingEnvironment没有意义)当我设置了多个db上下文时,这对我很有用。在仅使用主上下文的情况下,这不是必需的。然而,我还有一个名字叫EnvironmentName。这起作用的
publicstringenvironmentname{get;set;}=“TestEnvironment”当我设置了多个db上下文时,这对我很有用。在仅使用主上下文的情况下,这不是必需的。然而,我还有一个名字叫EnvironmentName。这起作用的
publicstringenvironmentname{get;set;}=“TestEnvironment”