0

I use AutoFac. I have to resolve a type with an explicit instance which I get from another service.

For example: I have an instance of type Client which I get from somewhere (not from the container).

I want to configure the Autofac container so that always when an object of type Client should be resolved, it should return my instance.

Problem is that I don't have this instance at the time, when I configure the container with the Containerbuilder - so I cannot use for example LambdaRegistration.

Is there another solution for solving my problem?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • 3
    Where is this object coming from such that it's NEITHER available before container creation NOR can it be obtained as the result of calling a method on a service that is registered with the container? – Ian Mercer Dec 30 '20 at 20:48
  • It is read and deserialized from the config. I read an Array of Client-Objects from the Config. After I execute a Service for each Client-Object - each in its own scope. This service uses other services which needs Property-Values of the Client-Object. Now I have thought it would be nice that I can register the Client-Object and this service can resolve it. – BennoDual Dec 30 '20 at 22:16

1 Answers1

0

You can do the following:

MyService service = null;

builder.Register(c => service).As<IMyService>();

// Later on
service = new MyService();

Depending on your needs there are quite some variations of this approach possible, such as:

  • Send a 'setter' delegate to some initialization code that will call the delegate after the service gets created, e.g. MyServiceInitializer.AfterInitialization(s => service = s);
  • Promote the service variable to a class property and provide that new wrapper to the initialization
  • Hide access to the service behind specific read and write abstractions, e.g. interface IMyServiceContext { IMyService Current { get; } } and interface IMyServiceSetter { void SetCurrent(IMyService service); }.
  • Prevent Autofac from accidentally resolving the service before it is initialized by throwing an exception instead of throwing null, e.g. Register(c => service ?? throw new InvalidOperationException("..."))

It's important to note, however, that in general, the creation of components should be fast and reliable. The fact that your component isn't available at startup is likely because it requires I/O to setup. This is a situation should should try to prevent, for instance by hiding it behind an abstraction completely. This allows you to implement a Proxy that allows the real service to be lazy loaded.

Hopefully this gives you some clues on how to solve this.

Steven
  • 166,672
  • 24
  • 332
  • 435