59

I'm very new to autofac so it's possible that I'm completely misusing it.

Let's say I have a class that has this structure:

public class HelperClass : IHelperClass
{
     public HelperClass(string a, string b)
     {
         this.A = a;
         this.B = b;
     }
}

and I have two classes that use that class, but require different defaults for the constructor. The second constructor is JUST for testing purposes -- we will always want a HelperClass in the "real" app.:

public class DoesSomething: IDoesSomething
{
     public DoesSomething()
         : this(new HelperClass("do", "something"));
     {

     }

     internal DoesSomething(IHelperClass helper)
     {
          this.Helper = helper;
     }
}

public class DoesSomethingElse : IDoesSomethingElse
{
     public DoesSomethingElse()
         : this(new HelperClass("does", "somethingelse"));
     {

     }

     internal DoesSomethingElse(IHelperClass helper)
     {
          this.Helper = helper;
     }
}

Here's my AutoFac module:

public class SomethingModule: Module
{
    protected override void Load(ContainerBuilder builder)
    {
         builder.RegisterType<DoesSomething>().As<IDoesSomething>();
         builder.RegisterType<DoesSomethingElse>().As<IDoesSomethingElse();
    }
}

My question(s):

  1. When I call resolve on DoesSomething or DoesSomethignElse -- will it resolve the internal constructor instead of the public one? Do I need to leave IHelperClass unregistered?
  2. If yes, how do I make it pass different parameters to each instance of IHelperClass depending on whether it's used in DoesSomething or DoesSomethingElse?
4
  • 6
    It's very strange to have such a half-loosely-coupled design. It makes things more difficult. Your public interfaces basically claim that your classes have no dependencies, but in fact they seem to depend on IHelper. If so, you'd better make the dependencies visible. Why don't you just remove your parameterless constructor, make the other one public and have your module configuration provide required parameters. You can use WithParameter as Daniel Hilgarth has suggested. Jan 30, 2012 at 16:39
  • @PavelGatilov Thanks, that makes sense. My thinking was that each class "knows" what parameters it needs to pass to the the helper, so it wouldn't make sense passing it in from the outside in the module configuration.
    – Paul
    Jan 30, 2012 at 16:51
  • 3
    If a class knows what parameters it needs, it couples it to the parameters and breaks the whole idea of Inversion of Control. You should on the contrary design your classes agnostic to their parameters implementations. It's configuration that should know which specific classes to compose together. Jan 30, 2012 at 17:12
  • However, you might need to hide some parts of configs to make sure you solely control the composition inside your module. This is OK. It might be done by making DoesSomething and DoesSomethingElse classes' constructors internal and using FindConstructorsWith on registration to allow Autofac to resolve them. Then you'll be sure that in partial trust noone outside your assembly will create your classes, but everyone will be able to resolve the classes and use them. Yet, in full trust this won't work. Nothing will. Hope this helps. Jan 30, 2012 at 17:16

5 Answers 5

67

You can always use the WithParameter method to explicitly specify a constructor parameter:

builder.RegisterType<DoesSomething>()
       .As<IDoesSomething>()
       .WithParameter("helper", new HelperClass("do", "something"));

builder.RegisterType<DoesSomethingElse>()
       .As<IDoesSomethingElse>()
       .WithParameter("helper", new HelperClass("do", "somethingelse"));

As far as I can tell there is no need for an interface for HelperClass because it essentially is just a value holder.

For this to work you would need to make the internal constructor public, I think.

3
  • In my "real" code, IHelper is actually an OAuth client, with some configuration values taken in the constructor for specific OAuth services. I'm trying to wrap my head around whether I need to register that class too in Autofac, or just pass it in my first constructor like I do now. Any idea what would be considered "correct"?
    – Paul
    Jan 30, 2012 at 16:30
  • 1
    I would still go with the approach I showed you - or something similar. When I have a class that needs values in its constructor - and your OAuth client is a value in that sense - I just new up an instance of that class and pass the constructor parameters and register that instance with the ContainerBuilder in the composition root. Jan 30, 2012 at 16:44
  • what is there inside HelperClass class, I want to pass connection string a dynamic parameter can you help me
    – Neo
    Mar 23, 2015 at 11:40
66

There are two ways to pass parameters in Autofac:

When you are registering the component:

When you register components, you have the ability to provide a set of parameters that can be used during the resolution of services based on that component. Autofac offers several different parameter matching strategies:

  • NamedParameter - match target parameters by name
  • TypedParameter - match target parameters by type (exact type match required)
  • ResolvedParameter - flexible parameter matching

    // Using a NAMED parameter:
    builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter("configSectionName", "sectionName");// parameter name, parameter value. It's the same of this: new NamedParameter("configSectionName", "sectionName")
    
    // Using a TYPED parameter:
    builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(new TypedParameter(typeof(string), "sectionName"));
    
    // Using a RESOLVED parameter:
    builder.RegisterType<ConfigReader>()
       .As<IConfigReader>()
       .WithParameter(
         new ResolvedParameter(
           (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "configSectionName",
           (pi, ctx) => "sectionName"));
    

    NamedParameter and TypedParameter can supply constant values only.

    ResolvedParameter can be used as a way to supply values dynamically retrieved from the container, e.g. by resolving a service by name.

In case you want to pass as parameter a service that is already registered, eg, IConfiguration, you can resolve the parameter as I show below:

    builder.RegisterType<Service>()
           .As<Iervice>()
           .WithParameter((pi, ctx) => pi.ParameterType == typeof(IConfiguration) && pi.Name == "configuration",
                          (pi, ctx) => ctx.Resolve<IConfiguration>());

When you are resolving the component:

One way to pass parameter at runtime in Autofac is using the Resolve method. You could create a class like this:

public class ContainerManager
{
  public IContainer Container {get;set;}
  //...
  public T[] ResolveAllWithParameters<T>(IEnumerable<Parameter> parameters)
  {
    return Container.Resolve<IEnumerable<T>>(parameters).ToArray();
  }
}

Parameter is an abstract class that belongs to Autofac, you can use the NamedParameter class to pass the parameters that you need. You can use the ContainerManager class as I show below:

    public T[] ResolveAllWithParameters<T>(IDictionary<string,object> parameters )
    {
        var _parameters=new List<Parameter>();
        foreach (var parameter in parameters)
        {
            _parameters.Add( new NamedParameter(parameter.Key, parameter.Value));
        }
        return ContainerManager.ResolveAllWithParameters<T>(_parameters);
    }

This way you can pass the parameters at runtime using a Dictionary<string, object> when you are resolving an specific component.

Using an Extension Method could be even more simple:

public static class ContainerExtensions
{
    public static T[] ResolveAllWithParameters<T>(this IContainer Container, IDictionary<string, object> parameters)
    {
        var _parameters = new List<Parameter>();
        foreach (var parameter in parameters)
        {
            _parameters.Add(new NamedParameter(parameter.Key, parameter.Value));
        }
        return Container.Resolve<IEnumerable<T>>(_parameters).ToArray();
    }
}
4
  • First, thanks for your guides that link to the documentation. Here I have a question, I am working on Web API AutoFac. I would like to pass parameter on run time (eg: a token). It is noted that 'Passing parameter to Resolve' would do the job. BUT, where should I perform the 'Resolve'? Since it is on run time, that means it isn't on the Startup.cs/Global.asax right?
    – zeroflaw
    Jan 25, 2018 at 3:41
  • To rephrase, I have a Web API that uses a Service which contains a parameter passed on runtime. So, the question is, "How/Where to pass parameter to that Service (Resolve)?"
    – zeroflaw
    Jan 25, 2018 at 3:53
  • Is it possible to pass only a sub set of parameters ? e.g if i have firs param as some class that is already registered and two others as some primitive types can I use WithParametes adding just the two primitive assuimig that Autofac will retrieve the first one as is registered ? or WithParameters requires all parameters to be added ?
    – IronHide
    Oct 11, 2018 at 6:29
  • Excellent. Very helpful ! Thanks. Dec 4, 2020 at 20:54
12

Autofac does not use non-public constructors. By default, it only finds public ones and simply doesn't see the others. Unless you use .FindConstructorsWith(BindingFlags.NonPublic), it will see only public constructors. Therefore your scenario should work as you expect it to do.

3
  • 1
    When I add that to RegisterType or RegisterTypeAs method, it says FindConstructionsWith doesn't that BindingFlags.NonPublic in its parameter.
    – MIWMIB
    Jun 30, 2015 at 1:54
  • 3
    @FrankGorman (or really mostly others looking for this answer). You can add a IContructorFinder from here: github.com/mthamil/TFSTestCaseAutomator/blob/master/… Oct 15, 2015 at 9:05
  • @TroelsLarsen - Exactly what I've been searching for for some time. Thanks mate! Apr 11, 2017 at 2:08
4

Yes, it is possible to pass only a sub set of parameters:

public Contract(IPerson person, String name)
{ 
    this.Person = person;
    person.Name = name;
}

....

// this uses the person/name ctor. Person is factored and injected by the contianer
List<Parameter> parameters = new List<Parameter>();
parameters.Add(new NamedParameter("name", "cloe"));
contract = scope.Resolve<IContract>(parameters);
0

If you only want to pass arguments to the constructor of any resolved component after the Autofac container had built, try out delegate factory which behaviors just like method ResolveAllWithParameters() in @ocuenca 's answer, but more convenience to use and write less:

public class HelperClass
{
    // Note both the TYPES and NAMES in the delegate match
    // the parameters in the constructor. This is important!
    public delegate HelperClass New(string a, string b = default);

    public HelperClass(string a, string b) { }
}
builder.RegisterType<HelperClass>();
builder.RegisterType<DoesSomething>();
public class DoesSomething
{
    private readonly HelperClass _helper;

    public DoesSomething(HelperClass.New helperFactory)
    {
        _helper = helperFactory("value_of_a_param");
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.