简单喷油器-“懒惰"喷油器实例化一个依赖于首次使用的单例 [英] Simple Injector - "Lazy" Instantiate a singleton that has dependencies on first use

查看:72
本文介绍了简单喷油器-“懒惰"喷油器实例化一个依赖于首次使用的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个控制台应用程序,可以执行许多不同的操作.很多不同的事情,它的作用取决于我们作为命令行参数传入的内容.它最初是用这种方式构建的,因此只占用了我们构建服务器中的一个许可位置,建议拆分时我遇到了很多阻力.

We have a console app that does a lot of different things. A LOT of different things, and what it does depends on what we pass in as command line parameters. It was originally built this way so that it only took up one licensed spot in our build server, and I've met with a bunch of resistance when suggesting splitting it out.

此应用程序将简单注入器用于IoC ...问题是,我们有很多单例服务,这些服务未用于任何给定的操作,并且每次使用时都加载...这非常烦人.我只想加载实际用于任何给定操作的依赖项.

This app uses Simple Injector for IoC... the problem is, we've got a bunch of singleton services that are not used for any given operation, and they load with every use... this is annoyingly slow. I only want to load the dependencies that are actually used for any given operation.

Lazy< TService> 上似乎有很多文档,但是在实践中,这非常令人沮丧.似乎Lazy构造函数没有意识到正在使用的容器,因此它必须使用无参数构造函数或值工厂,而这些工厂似乎也没有意识到依赖项所在的容器.

It looks like there's a lot of documentation around the Lazy<TService>, but in practice it's pretty frustrating. It seems that Lazy constructor is unaware of the container it's being used in, so it must use a parameterless constructor or a value factory that also seems unaware of the container the dependencies are in.

我想用Simple Injector做些什么吗?我一直在玩各种版本的Lazy泛型,但似乎无法获得想要的东西.

Is what I want to do possible with Simple Injector? I've been playing with all sorts of versions of the Lazy generic but I can't seem to get what I want.

推荐答案

简单注入器允许您注册工厂代表.

// From the link above, chapter "Lazy"
container.Register<Lazy<IMyService>>(
    () => new Lazy<IMyService>(container.GetInstance<RealService>));

另一种可能性是使用装饰器.Simple Injector也允许您执行此操作.相对于第一个解决方案(必须调用 lazyService.Value.DoSomething(); )的优点是,您可以使此更改透明.IE.装饰器实现服务,您可以调用 decoratedService.DoSomething();

Another possibility is to use a decorator. Simple Injector allows you to do this as well. The advantage over the first solution (where you have to call lazyService.Value.DoSomething();) is, that you can make this change transparent. I.e. the decorator implements the service and you can call decoratedService.DoSomething();

这篇关于简单喷油器-“懒惰"喷油器实例化一个依赖于首次使用的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆