简体   繁体   English

当依赖关系是循环的时,如何在Startup.cs中实现依赖注入?

[英]How to implement dependency injection in Startup.cs when dependencies are circular?

I have a MyProject project where I have IMyService interface and MyService class that implements IMyService . 我有一个MyProject项目,我有IMyService接口和实现IMyService MyService类。 In Startup.cs class I dependency injection them: 在Startup.cs类中,我依赖注入它们:

// MyProject project | Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMyService, MyService>();
}

Because MyService has many dependencies (makes many REST calls to 3rd party etc.) I would like to create a stub version of it for development environment. 因为MyService有很多依赖项(对第三方进行许多REST调用等),我想为开发环境创建它的存根版本。 I created new MyStubsProject that references to MyProject . 我创建了引用MyProject的MyStubsProject And I implemented stub version of IMyService to MyStubsProject : 而我实现的存根版本IMyServiceMyStubsProject:

// MyStubsProject project
public class MyStubService : IMyService
{
    ...
}

So now I want to add dependency injection to Startup.cs class: 所以现在我想向Startup.cs类添加依赖注入:

// MyProject project | Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    if (isDevelopmentEnvironment)
        services.AddScoped<IMyService, MyStubService>();
    else
        services.AddScoped<IMyService, MyService>();
}

But if I add that, there will be circular dependency between MyProject and MyStubsProject . 但是,如果我添加它, MyProjectMyStubsProject之间将存在循环依赖。

How should I implement reference to the class MyStubService or MyStubsProject project in Startup.cs? 我应该如何实现对Startup.cs中的类MyStubServiceMyStubsProject项目的引用?

The best answer is probably to extract your service stuff into a separate project - at least the service contracts ( IMyService ). 最好的答案可能是将您的服务提取到一个单独的项目中 - 至少是服务合同( IMyService )。 That should let both your existing projects reference the service contracts without any conflicts. 这应该让您的现有项目都引用服务合同而不会发生任何冲突。 If you want to add other interfaces, or add other implementations of the same interface, this will now be easy too. 如果您想添加其他接口,或添加相同接口的其他实现,现在也很容易。

An additional benefit may be a better overall architecture: Keeping contracts in a separate project, which contains no actual logic (only interfaces) will generally result in better organized and cleaner code. 另一个好处可能是更好的整体架构:将合同保存在一个单独的项目中,其中不包含任何实际逻辑(仅接口)通常会产生更好的组织和更清晰的代码。

You can use the precompiler directive #if to determine if your project is set to debug or release. 您可以使用预编译器指令#if来确定您的项目是设置为调试还是释放。 The compiler will do the rest! 编译器将完成剩下的工作!

// MyProject project | Startup.cs
public void ConfigureServices(IServiceCollection services)
{
#IF DEBUG
        services.AddScoped<IMyService, MyStubService>();
#ELSE
        services.AddScoped<IMyService, MyService>();
#ENDIF
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM