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

C# 在简单注入器中实现惰性代理,c#,generics,dependency-injection,simple-injector,C#,Generics,Dependency Injection,Simple Injector,简单的注入器记录了如何实现惰性依赖项。但是,此示例仅涵盖注册简单接口(IMyService)。这将如何与开放泛型(例如,IMyService)一起工作 这是我现有的注册信息: container.Register(typeof(IDbRepository<>), typeof(DbRepository<>)); container.Register(typeof(idbreepository),typeof(DbRepository)); 显然,以下代码没有编译,因为

简单的注入器记录了如何实现惰性依赖项。但是,此示例仅涵盖注册简单接口(
IMyService
)。这将如何与开放泛型(例如,
IMyService
)一起工作

这是我现有的注册信息:

container.Register(typeof(IDbRepository<>), typeof(DbRepository<>));
container.Register(typeof(idbreepository),typeof(DbRepository));
显然,以下代码没有编译,因为我没有指定泛型类型:

container.Register(typeof(IDbRepository<>),
    () => new LazyDbRepositoryProxy<>(new Lazy<IDbRepository<>(container.GetInstance<>)));
container.Register(typeof(IDbRepository),

()=>新的LazyDbRepositoryProxy(新的Lazy像你建议的那样的代码结构不能用C#来表达。但是通过对设计做一点小小的改变,你可以优雅地解决你的问题

诀窍是将
容器
注入到
LazyDbRepositoryProxy
中。这样,简单的注入器就可以使用自动连接轻松构造新的
LazyDbRepositoryProxy
实例,从而避免您必须注册委托(这对于打开的泛型类型不起作用)

因此,将您的
LazyDbRepositoryProxy
更改为以下内容:

//由于此类型取决于DI库,因此应将此类型放在
//合成根。
公共类LazyDbRepositoryProxy:IDbRepository
{
私有只读文件;
公共LazyDbRepositoryProxy(容器)
{
this.wrapped=newlazy(container.GetInstance));
}
}
并按以下方式注册您的类型:

container.Register(typeof(DbRepository));
Register(typeof(idbreepository),typeof(LazyDbRepositoryProxy));

Hi@steven。我尝试了上面的方法,对代码做了一点小小的修改:
public lazydrepositoryproxy(Container-Container){wrapped=new Lazy(()=>Container.GetInstance());}
一切正常-谢谢!
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);