【发布时间】:2026-02-15 01:55:01
【问题描述】:
在我的应用程序中,我有许多服务,我使用以下模式: 在与接口相同的文件中,我定义了一个由 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 专家关于此模式的 cmets。
【问题讨论】:
-
这听起来很像
Lazy<T>
标签: c# inversion-of-control ioc-container simple-injector