c# - 在简单注入器中实现惰性代理
问题描述
Simple Injector 文档描述了如何实现惰性依赖。然而,这个例子只涉及注册一个简单的接口 ( IMyService
)。这将如何与开放通用(EG。IMyService<T>
)一起工作?
这是我现有的注册:
container.Register(typeof(IDbRepository<>), typeof(DbRepository<>));
显然,以下代码无法编译,因为我没有指定泛型类型:
container.Register(typeof(IDbRepository<>),
() => new LazyDbRepositoryProxy<>(new Lazy<IDbRepository<>(container.GetInstance<>)));
这在 Simple Injector 中可行吗?我只能看到 Register 的以下覆盖,其中不允许传入 func / instanceCreator:
public void Register(Type openGenericServiceType, params Assembly[] assemblies);
public void Register(Type openGenericServiceType, IEnumerable<Assembly> assemblies);
public void Register(Type openGenericServiceType, Assembly assembly, Lifestyle lifestyle);
public void Register(Type openGenericServiceType, IEnumerable<Assembly> assemblies, Lifestyle);
public void Register(Type openGenericServiceType, IEnumerable<Type> implementationTypes, Lifestyle);
public void Register(Type openGenericServiceType, IEnumerable<Type> implementationTypes);
解决方案
您建议的代码构造不是您可以用 C# 表达的。但是通过对你的设计做一个小的改变,你可以优雅地解决你的问题。
诀窍是注入Container
你的LazyDbRepositoryProxy<T>
. 这样,Simple Injector 可以LazyDbRepositoryProxy<T>
使用自动装配轻松构造新实例,从而避免您必须注册委托(这不适用于开放通用类型)。
因此,将您的更改LazyDbRepositoryProxy<T>
为以下内容:
// As this type depends on your DI library, you should place this type inside your
// Composition Root.
public class LazyDbRepositoryProxy<T> : IDbRepository<T>
{
private readonly Lazy<DbRepository<T>> wrapped;
public LazyDbRepositoryProxy(Container container)
{
this.wrapped = new Lazy<IMyService>(container.GetInstance<DbRepository<T>>));
}
}
并按如下方式注册您的类型:
container.Register(typeof(DbRepository<>));
container.Register(typeof(IDbRepository<>), typeof(LazyDbRepositoryProxy<>));
推荐阅读
- swiftui - SwiftUI - 属性更改时视图不刷新
- c++ - 错误:没有匹配函数调用 'es_queue::set_rpc_vector(std::vector >&, std::__cxx11::string)'
- angular6 - 如何在 Angular 8 中实现 PayUMoney 支付网关
- reactjs - 如何使用 Enzyme 和 Jest 测试回调 refs
- php - 回显 PHP 字符串值作为悬停时的标题?
- c# - RDLC 导出为具有高分辨率背景图像的 pdf
- reactjs - 无法使用 useState 更新文本
- gdb - 使用 J-Link 在 PlatformIO 上调试失败
- html - XPATH 仅返回特定行标题的值,而不是所有行
- java - DateTimeFormatter 和 ISO 8601 字符串