TAGS :Viewed: 8 - Published at: a few seconds ago

[ Autofac inject enumeration ]

How can I inject enumeration value into constructor?

my constructor is:

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

Where my search type is:

public enum SearchType 
{          
    Document,               
    PageSearch,  
}

My autofac registration:

builder.Register(x => new AutoComplete(SearchType.Document,  

              x.ResolveNamed<ISearchResultParser>NamedAutofacInstances.AutoCompleteSearchResultParser),                 invalidSearchTerms);

Question:

What is the correct way of implementing enum?

Answer 1


How about something like this?

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,
}