2013-11-28 132 views
1

我怎麼能注入枚舉值成一個構造?Autofac注入枚舉

我的構造函數是:

public AutoComplete(SearchType searcherType, ISearchResultParser searchResultParser, string[] ignoreSearchTerms = null) 

凡我搜索類型是:

public enum SearchType 
{   
    Document,    
    PageSearch, 
} 

我Autofac登記:

builder.Register(x => new AutoComplete(SearchType.Document, 
    x.ResolveNamed<ISearchResultParser>(NamedAutofacInstances.AutoCompleteSearchResultParser), 
    invalidSearchTerms); 

問:

執行枚舉的正確方法是什麼?

+0

您的構造函數是自動完成但您註冊AutoCompleteForExamine。可以嗎? –

+0

@AlexandrNikitin Thnx指出,這是錯字 – cpoDesign

回答

1

怎麼這樣呢?

using Autofac; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 

[TestClass] 
public class UnitTest1 
{ 
    [TestMethod] 
    public void Test1() 
    { 
     var builder = new ContainerBuilder(); 
     builder.RegisterType<AutoComplete>() 
      .WithParameter((pi, c) => pi.ParameterType == typeof(SearchType), 
          (pi, c) => SearchType.Document); 
     var container = builder.Build(); 
     var autoComplete = container.Resolve<AutoComplete>(); 
     Assert.AreEqual(SearchType.Document, autoComplete.SearcherType); 
    } 
} 

public class AutoComplete 
{ 
    public AutoComplete(SearchType searcherType) 
    { 
     SearcherType = searcherType; 
    } 
    public SearchType SearcherType { get; private set; } 
} 

public enum SearchType 
{ 
    Document, 
    PageSearch, 
} 
+0

看起來很great.thnx – cpoDesign