C# 依赖注入 - 良好实践

C# Dependency Injection - good practices

我在理解如何创建可注射 classes 时遇到了一些问题……

这是我的例子:

public interface IService
{
  string FindSomeData()
}

现在我们创建一个实现接口的class:

public class FolderService : IService
{
  private string _path;

  public FolderService(string path)
  {
    _path = path;
  }

  public string FindSomeData()
  {
    //Open a folder using _path and find some data
  }
}

也许还有其他 class:

public class DbService : IService
    {
      private MyConnectionClass _connection;

      public DbService(MyConnectionClass connection)
      {
        _connection = connection;
      }

      public string FindSomeData()
      {
        //Connect to database using _connection object and find some data
      }
    }

现在我想将 classes 之一添加到 IoC Container e.x.:

if (InDebug)
 SimpleIoc.Default.Register<IService, FolderService>();
else
 SimpleIoc.Default.Register<IService, DbService>();

知道我有问题。 当我想将此对象传递给其他一些 classes:

的构造函数时
public MyViewModel(IService service)
{
 _service = service;
}
// Read folder name from TextBox on View and then call _service.FindSomeData

然后我想在这种情况下将用户选择的路径传递给 IService 对象 (FolderService)。 我应该如何以正确的方式执行此操作(根据 SOLID 和其他良好的实践模式……)?

一次是传递字符串(文件夹路径),一次是MyConnectionClass(如果连接到数据库)。 做这类事情的最佳方法是什么?

此致, 米甲

您可以将文件夹路径 provide/change 逻辑封装到单独的提供程序中,例如 IFolderPathProvider 并将其注入 FolderService

public interface IFolderPathProvider {
    string GetFolderPath();
    void SetFolderPath(string);
}

public class FolderPathProvider : IFolderPathProvider  {
    ...
}

public class FolderService : IService
{
  private IFolderPathProvider _folderPathProvider;

  public FolderService(IFolderPathProvider folderPathProvider)
  {
    _folderPathProvider = folderPathProvider;
  }

  public string FindSomeData()
  {
    string path = _folderPathProvider.GetFolderPath();
    //Open a folder using path and find some data
  }
}

当用户更改路径时,将 IFolderPathProvider 注入处理程序并调用 SetFolderPath。同样,您可以创建 IDbConnectionProvider。根据情况,它们可以合并为一个 DataConfigProvider 但我不确定您到底需要什么;主要思想是将 folderpath/dbconnection 更改逻辑与服务分开并继续使用依赖注入。