1

I have the following class:

public class A
{
    private string name;
    private int id;

    public A([KeyFilter("name")] string name, [KeyFilter("id")] int id)
    {
        this.name = name;
        this.id = id;
    }
}

I want to inject the dependencies using autofac. Both parameters will be taken from a config file. Here is my code to initialize the class.

public IContainer Initialize()
{
    ContainerBuilder builder = new ContainerBuilder();
    string name = ConfigurationManager.AppSettings["Name"];
    builder.RegisterInstance(name).Keyed<string>("name");
    int id = int.Parse(ConfigurationManager.AppSettings["Id"]);
    builder.RegisterInstance(id).Keyed<int>("id");

    builder.RegisterType<A>().WithAttributeFiltering();
    return builder.Build();
}

The code above does not compile due to the error "Type int must be a reference type in order to use it as parameter T ...". I realized that I need another mechanism to inject the integer. I tried other functions from Builder and even made a research in the autofac documentation without luck.

A solution here could be to expect a string id (instead of int id) an inject as string and finally parse it inside the class A, but I do not like that solution so much. Any suggestion?

afonte
  • 938
  • 9
  • 17

1 Answers1

2

You can use the Register method taking a lambda function :

int id = int.Parse(ConfigurationManager.AppSettings["Id"]);
builder.Register(c => id).Keyed<int>("id"); 

The RegisterInstance method has a class constraint because this method is intended to share the same instance of an object which can be done with struct. See Cannot register a struct instance with autofac for more information on why you can't register a struct instance.

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
  • Thanks, that way did the trick. I read the other post and understood why I cannot register a struct. – afonte Jun 27 '17 at 14:38