在简单注入器中实现惰性代理

Implement Lazy Proxy in Simple Injector

Simple Injector 文档 describe 如何实现延迟依赖。但是,此示例仅涵盖注册一个简单的接口 (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<>));