Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autofac registration issue in release v2.4.5.724

Tags:

autofac

I have the following registration

builder.Register<Func<Type, IRequestHandler>>(
          c => request => (IRequestHandler)c.Resolve(request));

Basically I am trying to register a factory method that resolves an instance of IRequestHandler from a given type.

This works fine until the version 2.4.3.700. But now I am getting a the following error..

Cannot access a disposed object. Object name: 'This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c', or resolve a Func<> based factory to create subsequent components from.'.

UPDATE

I was trying to limit autofac's exposure to the rest of the projects in the solution. Nick, thanks for the hint, now my registration looks like this...

 builder.Register<Func<Type,IRequestHandler>>(c =>  
         { 
           var handlers = c.Resolve<IIndex<Type,RequestHandler>>(); 
           return  request => handlers[request];  
         });
like image 909
chandmk Avatar asked Mar 21 '11 21:03

chandmk


1 Answers

The c in this expression is a temporary, so this code while previously functional, is broken. Autofac 2.4.5 detects this problem while earlier versions silently ignored it.

To fix the issue, explicitly resolve IComponentContext:

builder.Register<Func<Type, IRequestHandler>>(c => {
    var ctx = c.Resolve<IComponentContext>();
    return request => (IRequestHandler)ctx.Resolve(request));
});

The functionality you're emulating here might be better represented using keys and indexes, e.g. see Interrupted chain of IoC or http://code.google.com/p/autofac/wiki/TypedNamedAndKeyedServices.

like image 59
Nicholas Blumhardt Avatar answered Nov 05 '22 13:11

Nicholas Blumhardt