在我的應用我有很多的服務,我用的是以下模式: 在同一文件中,我定義它是由IoC容器如下控制的靜態工廠方法的接口:IoC的實例化最新時間可能
public interface ISomethingService {
Task DoSomethingAsync(int id);
}
public class SomethingServicFactory : ServiceFactory<ISomethingService > { }
public class ServiceFactory<T>
{
public static Func<T> CreateClosure;
public T GetDefault() => CreateClosure();
}
創建和配置IoC容器後:
SomethingServicFactory .CreateClosure =() =>
Container.GetInstance<ISomethingService >();
在我的應用。稍後,當我需要一個SomethingService:
var somethingService= new SomethingService().GetDefault();
這使我可以推遲創建,直到最後一刻仍然控制使用容器的服務創建。我剛開始使用SimpleInjector。 更重要的是,它允許我創建服務實例,並輕鬆傳遞參數,同時控制IoC。
這個模式幫助我的一個很好的例子是需要填充數據的WPF XAML實例化用戶控件(即從數據庫查找值)。在後面的代碼中,我能夠輕鬆創建一個DbContext並從數據庫中獲取數據。但是,我也在整個應用程序中使用它。
我擔心我錯過了使用此模式的重大設計/體系結構問題,我正在尋找IoC專家對此模式的評論。
這聽起來很像'懶惰' –
Nkosi