在我的应用程序中,我有许多服务,我使用以下模式:在与接口相同的文件中,我定义了一个静态工厂方法,该方法由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();
}
Run Code Online (Sandbox Code Playgroud)
创建和配置IoC容器后:
SomethingServicFactory .CreateClosure = () =>
Container.GetInstance<ISomethingService >();
Run Code Online (Sandbox Code Playgroud)
稍后在我的应用程序中,当我需要SomethingService时:
var somethingService= new SomethingService().GetDefault();
Run Code Online (Sandbox Code Playgroud)
这允许我将创建推迟到最后一刻,但仍然使用容器控制服务创建.我刚开始使用SimpleInjector.更重要的是,它允许我创建服务实例并轻松传递参数,同时控制IoC.
这个模式帮助我的一个很好的例子是WPF XAML实例化的用户控件,它需要填充数据(即数据库中的查找值).在后面的代码中,我能够轻松地创建DbContext并从数据库中获取数据.但是,我也开始在整个应用程序中使用它.
我担心通过使用这种模式我错过了重大的设计/架构问题,我正在寻找IoC专家对此模式的评论.