【问题标题】:Implement Lazy Proxy in Simple Injector在简单注入器中实现惰性代理
【发布时间】:2019-03-18 15:04:04
【问题描述】:

Simple Injector 文档describe 如何实现惰性依赖。然而,这个例子只涉及注册一个简单的接口(@98​​7654322@)。这将如何与开放泛型 (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# generics dependency-injection simple-injector


    【解决方案1】:

    您建议的代码结构不是您可以用 C# 表达的。但是,通过对您的设计进行微小的更改,您就可以优雅地解决您的问题。

    诀窍是将Container 注入您的LazyDbRepositoryProxy&lt;T&gt;。这样一来,Simple Injector 可以使用自动连接轻松构造新的 LazyDbRepositoryProxy&lt;T&gt; 实例,从而避免您必须注册委托(这不适用于开放泛型类型)。

    因此,将您的 LazyDbRepositoryProxy&lt;T&gt; 更改为以下内容:

    // 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<>));
    

    【讨论】:

    • 嗨@steven。我已经尝试了上述方法,并对代码进行了小幅更正:public LazyDbRepositoryProxy(Container container) { wrapped = new Lazy&lt;IDbRepository&lt;T&gt;&gt;(() =&gt; container.GetInstance&lt;DbRepository&lt;T&gt;&gt;()); } 一切正常 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-07
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多