Autofac and Func factories

You are calling secVMFactory outside of your FirstViewModel constructor so by that time the ResolveOperation is disposed and in your factory method the c.Resolve will throw the exception.

Luckily the exception message is very descriptive and telling you what to do:

When registering components using lambdas, the IComponentContext ‘c’
parameter to the lambda cannot be stored. Instead, either resolve
IComponentContext again from ‘c’

So instead of calling c.Resolve you need to resolve the IComponentContext from c and use that in your factory func:

builder.Register<Func<IEventAggregator, SecondViewModel>>(c => {
     var context = c.Resolve<IComponentContext>();
     return ea => { 
          return new SecondViewModel(context.Resolve<IEventAggregator>(), ea); 
     };
});

Leave a Comment