Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return NULL in an Autofac registration?

Is there a way to return null with autofac? I get a exception if I do this.

In some cases I cant resolve a object and should return null.

m_builder.Register < IMyObject > ((c, p) => {
  //do something

  if (...) {
    //cant create/resolve object (error case)
    return null;
  } else {
    return new IMyObject();
  }

}).InstancePerHttpRequest();

Is there a build-in way to do this with autofac?

Edit: I want to return null. Or do something else to inform the user that the creation was not successful. If I return null this exception will be thrown:

DependencyResolutionException:

A delegate registered to create instances of 'IMyObject' returned null.

Stacktrace:

at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable
1 parameters)
at Autofac.Core.Resolving.InstanceLookup.b__0()
at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func1 creator)
at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable
1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable
1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, Parameter[] parameters)
at RestApi.Controllers.MyApiController.CreateEntityContext() in C:...

like image 687
user437899 Avatar asked Aug 13 '12 07:08

user437899


1 Answers

AFAIK, returning NULL in a registration will always throw an exception. For some ideas on how to handle that, check out this answer.

like image 179
Jim Bolla Avatar answered Oct 24 '22 03:10

Jim Bolla