问题描述
在中,我可以执行以下操作:
In Simple Injector I can do the following:
container.RegisterSingle<IAuctionContext>(() => new AuctionContext(
new Uri("http://localhost:60001/AuctionDataService.svc/")));
我在这里说的是当 IAuctionContext ,将其替换为新的
AuctionContext
。问题在于,通过调用 RegisterSingle
,将仅使用 AuctionContext
的单个实例。我希望它能够像上面那样传递 Uri
参数,但没有单个实例,但每次都允许一个新实例。
What I am doing here is saying that when
IAuctionContext
is found, replace it with this new AuctionContext
. The problem is that with the call to RegisterSingle
, only a single instance of AuctionContext
will be used. What I'd like it to be able to pass in a Uri
parameter as above but not have the single instance but allow a new instance each time.
这怎么可能?
推荐答案
您要注入的值很简单编码的值。对于诸如硬编码值和配置值之类的常量值,只需使用
Register
方法:
The value you are trying to inject is a simple hard-coded value. For constant values like hard-coded values and configuration values, just use the
Register
method:
var uri = new Uri("http://localhost:60001/AuctionDataService.svc/");
container.Register<IAuctionContext>(() => new AuctionContext(uri));
Register
方法可确保新实例为每次返回。
The
Register
method ensures a new instance is returned each time.
当注入在应用程序过程中可能发生变化的值时,请阅读。
When it comes to injecting values that could change during the course of the application, please read this article about injecting runtime data.
这篇关于Simple Injector将硬编码的值传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!