Simple Injector将硬编码值传递给构造函数

Sac*_*nth 9 c# dependency-injection ioc-container simple-injector

Simple Injector中,我可以执行以下操作:

container.RegisterSingle<IAuctionContext>(() => new AuctionContext(
    new Uri("http://localhost:60001/AuctionDataService.svc/")));
Run Code Online (Sandbox Code Playgroud)

我在这里做的是说,IAuctionContext找到它后,用这个新的替换它AuctionContext.问题是,通过调用RegisterSingle,只会使用一个实例AuctionContext.我希望它能够传递Uri如上所述的参数但不具有单个实例但每次都允许新实例.

这怎么可能?

Ste*_*ven 18

您尝试注入的值是一个简单的硬编码值.对于硬编码值和配置值等常量值,只需使用以下Register方法:

var uri = new Uri("http://localhost:60001/AuctionDataService.svc/");

container.Register<IAuctionContext>(() => new AuctionContext(uri));
Run Code Online (Sandbox Code Playgroud)

Register方法确保每次都返回一个新实例.

在注入可能在应用程序过程中发生变化的值时,请阅读有关注入运行时数据的文章.