首页 > 解决方案 > 在简单注入器中实现惰性代理

问题描述

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#genericsdependency-injectionsimple-injector

解决方案


您建议的代码构造不是您可以用 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<>));

推荐阅读