我的目标是更改字符串参数:
Container
.RegisterInstance<string>("us", @"\\ad1\accounting$\Xml\qb_us.xml")
.RegisterInstance<string>("intl", @"\\ad1\accounting$\Xml\qb_intl.xml");
driver = Container.Resolve<LoaderDriver>(args[1]); // "us" or "intl"
结果是:
Resolution of the dependency failed, type = "QuickBooksService.LoaderDriver", name = "intl".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving QuickBooksService.LoaderDriver,intl
Resolving parameter "reader" of constructor QuickBooksService.LoaderDriver(QuickBooksService.LoaderInputReader reader, QuickBooksService.ILoader[] loaders)
Resolving QuickBooksService.LoaderInputReader,(none)
Resolving parameter "inputFile" of constructor QuickBooksService.LoaderInputReader(System.String inputFile, AccountingBackupWeb.Models.AccountingBackup.Company company, Qu
ickBooksService.eTargets targets)
Resolving System.String,(none)
这显然是错误的,但是这是我可以使其正常工作的唯一方法:
if (args[1] == "us")
Container
.RegisterType<LoaderInputReader>(
new InjectionConstructor(
@"\\ad1\accounting$\Xml\qb_us.xml",
new ResolvedParameter<Company>(),
new ResolvedParameter<eTargets>()
)
)
;
else if (args[1] == "intl")
Container
.RegisterType<LoaderInputReader>(
new InjectionConstructor(
@"\\ad1\accounting$\Xml\qb_intl.xml",
new ResolvedParameter<Company>(),
new ResolvedParameter<eTargets>()
)
)
;
else
throw new Exception("invalid company");
driver = Container.Resolve<LoaderDriver>();
最佳答案
这样的事情应该起作用:
container
.RegisterType<LoaderInputReader>(
"us",
new InjectionConstructor(
@"\\ad1\accounting$\Xml\qb_us.xml",
new ResolvedParameter<Company>(),
new ResolvedParameter<eTargets>()));
container
.RegisterType<LoaderInputReader>(
"intl",
new InjectionConstructor(
@"\\ad1\accounting$\Xml\qb_intl.xml",
new ResolvedParameter<Company>(),
new ResolvedParameter<eTargets>()));
这将命名每个
LoaderInputReader
注册。现在您可以像这样解决:var us = container.Resolve<LoaderInputReader>("us");
var intl = container.Resolve<LoaderInputReader>("intl");
关于c# - 用Unity改变构造函数注入(inject)的字符串参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8187750/