Chiune Sugihara
Chiune Sugihara

Reputation: 1229

Autofac Error for params Argument

I have a type Model that has a constructor:

Model(string name, IFoo dependency)

I want to use a factory to create instances of Model off of the container using a different value for name each time. To do this I register my Model type and then the factory like so:

var builder = new ContainerBuilder();
builder.RegisterType<Model>();`
var container = builder.Build();
var factory = builder.Resolve<Func<string, Model>>();

The problem comes in later where I have class Consumer that has the following constructor:

public Consumer(IFoo depedency, params Model[] optionalInputs)

When I go to resolve Consumer I get an exception because in order to get my factory I had to register Model even though I don't ever want to resolve it except through the factory. I don't want to use a NamedParameter or anything like that because there is no default instance to use, I just want any optional collections such as params Model[] ... to be set to an empty array when they are encountered. `

Upvotes: 0

Views: 94

Answers (1)

fknx
fknx

Reputation: 1785

You could change the registration of Consumer to specify how the instance shall be constructed:

builder.Register(c => new Consumer(c.Resolve<IFoo>()));

This way the params parameter will be ignored.

I just want any optional collections such as params Model[] ... to be set to an empty array when they are encountered.

From my point of view this sounds like a flaw in your design. You want Autofac to create your Consumer instance but you don't want it to set the optionalInputs parameter. In that case, why don't you simply remove the parameter altogether?

Update

Following your comment, I guess you could add an explicit registration for the Model[] type:

builder.RegisterInstance<Model[]>(Array.Empty<Model>());

I've tried this approach and it seems to achieve your goal.

Upvotes: 2

Related Questions