Register Container Itself Using Autofac

Your code is not safe because you register an instance before it has been initialized.

If you need to have access to the container inside a component (which is not a good idea) you can have a dependency on ILifetimeScope which have Resolve methods.

public class ManagmentServiceImp 
{
    public ManagmentServiceImp(ILifetimeScope scope)
    {
    }
}

ILifetimeScope is automatically registered within Autofac you don't need to add registration for it.

See Controlling Scope and Lifetime from Autofac documentation for more information.

By the way, it is not a good practice to have dependency on your IoC container. It looks like you use Service Locator anti-pattern. If you need the container to lazy load dependency, you can use composition with Func<T> or Lazy<T>

public class ManagmentServiceImp 
{
    public ManagmentServiceImp(Lazy<MyService> myService)
    {
        this._myService = myService; 
    }

    private readonly Lazy<MyService> _myService;
}

In this case, MyService will be created when you first access it.

See Implicit Relationship from the Autofac documentation for more information.


You can use this extension method:

public static void RegisterSelf(this ContainerBuilder builder)
{
    IContainer container = null;
    builder.Register(c => container).AsSelf().SingleInstance();
    builder.RegisterBuildCallback(c => container = c);
}

use it like this: builder.RegisterSelf();