Raskolnikov
Raskolnikov

Reputation: 4009

How to resolve list of dependencies in Autofac?

I want register type, than resolve type, and then register instance using resolved values. Something like this:

//Register type:
builder.RegisterType<ValidateImportMandatoryColumns>().Named<IValidateImport>("MandatoryColumn").As<IValidateImport>();
builder.RegisterType<ValidateImportNonMandatoryColumns>().Named<IValidateImport>("NonMandatoryColumns").As<IValidateImport>(); 

//Resolve
var t1 = Container.ResolveNamed<IValidateImport>("MandatoryColumn");
var t2 = Container.ResolveNamed<IValidateImport>("NonMandatoryColumns");

//Create list with resolved values:
List<IValidateImport> allValidators = new List<IValidateImport>(){t1,t2};

//Register Instance:
builder.RegisterInstance(allValidators).As<List<IValidateImport>>();

This is not working. I can't resolve and than register again. Do you know how to do this with Autofac? Maybe is approach wrong, so please tell me if you have better idea. Goal is to inject list of validators with different types that use same interface.

Upvotes: 2

Views: 1533

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16187

Autofac has built in support for collection. If you want to resolve all IValidateImport, you can resolve IEnumerable<IValidateImport>

var allValidators = container.Resolve<IEnumerable<IValidateImport>>(); 

See Implicit Relationship Types for more information for more information.


By the way, if you want to update a container, which is not required here, you can use the following piece of code.

var builder = new ContainerBuilder(); 
// do some registration 

var container = builder.Build();


var updater = new ContainerBuilder();
// do other registraitons

// update the container 
updater.Update(container);

Upvotes: 3

Related Questions