gpt4 book ai didi

c# - 使用接口(interface)属性和设计原则注入(inject)接口(interface)

转载 作者:行者123 更新时间:2023-11-30 22:21:51 25 4
gpt4 key购买 nike

我有一系列类,每个类根据其角色具有多个依赖项。这些依赖项被注入(inject)到构造函数中。一个例子是:

public class UserViewModel
{
//...
public UserViewModel(IDataService dataService,
INotificationService notificationService,
IDialogService dialogService,
INavigationService navigationService)
{
this.DataService = dataService;
this.NotificationService = notificationService;
this.DialogService = dialogService;
this.NavigationService = navigationService;
}
}

如您所见,需要设置多个参数。我可以编写如下界面:

public interface IInteractionService 
{
public INotificationService NotificationService { get; set; }
public IDialogService DialogService { get; set; }
public INavigationService { get; set; }
}

并将注入(inject)的 InteractionService 实现整体传递给 UserViewModel 的构造函数:

public UserViewModel(IDataService dataService, 
IInteractionService interactionService) {}

并像这样使用它:

this.InteractionService.NotificationService.Publish(message);

在设计模式/原则方面,使用包含接口(interface)属性的交互接口(interface)是否存在任何问题?还是有更好的方式来看待它?

感谢任何建议...

最佳答案

一般来说,你不应该创建内部有不同服务的“上帝”服务。它打破了单一响应原则 (SRP)。

但我不明白 DI 是如何针对服务实例向您注入(inject) null 的?也许您应该修正此行为以防止创建“上帝”服务?

关于c# - 使用接口(interface)属性和设计原则注入(inject)接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078858/

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