gpt4 book ai didi

asp.net - 如何使用 Startup.cs 和 Assembly 在 MSTest 项目中实现依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-05 08:08:31 25 4
gpt4 key购买 nike

在我们的应用程序中,我使用了 Visual Studio 2017 .NET Core 2。我在 Web 项目 Startup.cs 类中实现了依赖注入(inject)。我必须在新的测试项目中实现相同的功能。如何在测试项目中注入(inject)存储库的依赖项?

请看下面的代码片段

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;

namespace Kpmg.Kdat.Data.Services.Directory.Tests
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog()
.Build();
}
}

上面代码的目的是注入(inject)依赖。在 Startup.cs 中,我已经配置了所有依赖项。

在使用上面的代码时出现以下错误:

Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

我该如何解决这个问题?

最佳答案

为什么要在单元测试项目中包含以上内容?通常,您不必这样做。

如果你想要模拟依赖,在你的单元测试项目中你可以做这样的事情。

public class TestServiceModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(ctx =>
{
// Return mock implementation of IMyService
}).As<IMyService>()
.SingleInstance();

// Register your mock services like above
}
}

然后像这样使用

[TestInitialize]
public void Initialize()
{
var builder = new ContainerBuilder();
builder.RegisterModule<TestServiceModule>();
}

现在您可以使用 IMyService 了。

关于asp.net - 如何使用 Startup.cs 和 Assembly 在 MSTest 项目中实现依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com