Autofac and Func factories

后端 未结 1 381
难免孤独
难免孤独 2020-12-13 13:56

I\'m working on an application using Caliburn.Micro and Autofac.

In my composition root I\'m now facing a problem with Autofac: I have to inject the globally used IEv

相关标签:
1条回答
  • 2020-12-13 14:30

    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); 
         };
    });
    
    0 讨论(0)
提交回复
热议问题