C#依赖注入-良好做法

时间:2018-07-20 11:33:49

标签: c# dependencies inversion-of-control code-injection

我在理解如何创建可注射类方面遇到一些问题……

这是我的例子:

public interface IService
{
  string FindSomeData()
}

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

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
  }
}

也许还有其他课程:

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
      }
    }

现在我想向IoC Container e.x添加一个类:

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

知道我有问题。 当我想将此对象传递给其他一些类的构造函数时:

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

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

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

最好的问候, 米哈尔

1 个答案:

答案 0 :(得分:1)

您可以将文件夹路径提供/更改逻辑封装到一个单独的提供程序中,例如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,但我不确定您到底需要什么?主要思想是将文件夹路径/ dbconnection更改逻辑与服务分开,并继续使用依赖项注入。

相关问题