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.