2011-11-18 52 views
2
構造注入字符串參數

我的目標是改變一個字符串參數:變化與統一

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>(); 

回答

2

像這樣的東西應該工作:

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"); 
+2

您可以簡化這一點了,說:container.RegisterType ( 「我們」,新InjectionConstructor(字符串的typeof(公司)的typeof(eTargets));你只需要明確地使用ResolvedParameter,如果你正在解決一個命名的依賴關係。 –

+0

謝謝你們真的幫助我走出了noob區域 –

0

也許你可以改變

driver = Container.Resolve<LoaderDriver>(args[1]); // "us" or "intl" 

driver = Container.Resolve<LoaderDriver>(Container.Resolve<string>(args[1])) 

這需要的Resolve overload that takes a name,凡在你的情況下,名字來源於你的論點的優勢。