Rad*_*ski 1 c# nunit dependency-injection ioc-container .net-core
我对 .NET Core 还很陌生。如何在 NUnit 类库项目中定义DI容器?
我知道它是通过 完成的IServiceCollection,但由于没有任何Startup方法,我不知道在哪里获取实现此接口的实例。
我还希望能够从其他类库加载定义(作为测试的主题)。这应该更简单,因为我可以在该类库中创建一个静态方法,并使用一个参数IServiceCollection,但同样,我如何获取它?
一个附带问题是:我认为出于测试目的可以模拟某些接口,但是如何替换已经使用 of 的IServiceCollection方法(如AddSingletonor )创建的映射AddTransient?
有一个Remove方法,但没有记录。
IServiceCollection由类来实现ServiceCollecion。因此,如果您想为集成测试执行此操作,那么您可以使用该类ServiceCollection来创建您自己的ServiceProvider.
var services = new ServiceCollection();
services.AddTransient<IMyInterface, MyClass>();
services.AddScoped<IMyScopedInteface, MyScopedClass>();
...
var serviceProvider = sc.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)
您现在可以serviceProvider在测试中使用该实例来获取您的类:
var myClass = serviceProvider.GetService<IMyInterface>();
Run Code Online (Sandbox Code Playgroud)
如果您想模拟某些接口而不是使用真实的接口,那么您可以添加一个模拟,而不是将真实的类/接口添加到服务集合中:
mockInterface = new Mock<IMyInterface>();
sc.AddScoped<IMyInterface>(factory => mockInterface.Object);
Run Code Online (Sandbox Code Playgroud)