[英]IOC - How to handle changing dependencies
假設我們有以下服務類:
public class PersonService : IPersonService
{
private readonly IPersonRepository _repository;
public PersonService(IPersonRepository repository)
{
_repository = repository;
}
/* Interface members here... */
}
這個服務類依賴於IPersonRepository
。 在我們的示例中,此存儲庫將處理文件連接:
public class FilePersonRepository : IPersonRepository
{
private readonly string _filePath;
public FilePersonRepository (string filePath)
{
_filePath = filePath;
}
/* Interface members here... */
}
這個存儲庫依賴於一個文件路徑,需要它來確定應該在這個存儲庫中處理哪個文件。
這些類連接在一個容器中:
public static void ConfigureContainer(MyIocContainer container)
{
container.Register<IPersonRepository, FilePersonRepository>(@"C:\temp\file.txt");
container.Register<IPersonService, PersonService>();
container.Register<MainViewModel>();
}
現在,如果我使用靜態路徑(例如在配置文件中),一切都很好,該路徑僅注入一次到此類構造函數中。
但是如果我有一個ViewModel
會發生什么,它在整個應用程序中持續存在,並且這個使用注冊的服務類。 並且文件路徑必須通過打開文件夾對話框進行更改。 如何處理?
我認為在我的存儲庫中使用帶有 get/set 的Property
或創建一個引用static string
路徑的類可能不太干凈。
有什么建議?
如何解決您的問題有很多解決方案,不可能說哪一個是最好的。 但我很確定最佳實踐是避免動態依賴。
我個人會這樣做:
public interface IRepositoryConnectionString
{
void SetConnectionString(string connectionString);
}
public interface IPersonRepository : IRepositoryConnectionString ...
public class FilePersonRepository : IPersonRepository
{
/* file related private fields here */
public FilePersonRepository ()
{
SetConnectionString(ConfigurationManager.ConnectionStrings[
"FilePersonRepository.ConnectionString"]);
}
public SetConnectionString(string connectionString)
{
/* do all required stuf like flush previous file, open file, etc... */
}
/* Interface members here... */
}
幾乎每個存儲都有某種連接字符串,所以這個接口應該適用於大多數其他可能的實現(Mongo、SQL、Azure Table)。
您的應用程序引導程序可以指定要使用的配置對話框。 例如作為:
container.Register<IPersonRepositoryConfigurationDailog, FileRepositoryConfigurationDialog>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.