title: AutoFac DI in static class
body: <p>We have a ASP.NET project, and we use AutoFac to DI. 
  We have a Service layer with all database queries and we need to make some queries in a static class.</p>
  
  <p>This is how we register the dependencies in the Global.asax:</p>
  
  <pre><code>public class Dependencies
  {
      public static void RegisterDependencies()
      {
          var builder = new ContainerBuilder();
  
          builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
  
          builder.RegisterModule(new ServiceModule());
          builder.RegisterModule(new EfModule());
  
          var container = builder.Build();
          DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
      }
  }
  
  public class ServiceModule : Autofac.Module
  {
      protected override void Load(ContainerBuilder builder)
      {
          builder.RegisterAssemblyTypes(Assembly.Load("MyApp.Service")).Where(t =&gt; t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
      }
  
  }
  
  public class EfModule : Autofac.Module
  {
      protected override void Load(ContainerBuilder builder)
      {
          builder.RegisterType(typeof(myDataContext)).As(typeof(IMyContext)).InstancePerLifetimeScope();
      }
  }
  </code></pre>
  
  <p>And this is how we access in the controller:</p>
  
  <pre><code>public class SomeController : Controller
  {
      private readonly IService1 _service1;
      private readonly IService2 _service2;
  
      public SomeController(IService1 service1, IService2 service2)
      {
          _service1 = service1;
          _service2 = service2;
      }
  
  
      public ActionResult Index()
      {
          var service = _service1.GetAll();
          ...
  
          return View(searchModel);
      }
  }
  </code></pre>
  
  <p>Now we need to retrieve data from the database in a static class, so we have to call our service layer, but we don't know how to do it...we have seen this, but I don't know if it is correct, but it works.</p>
  
  <pre><code>public static Test ()
  {
      ...
      var service1 = DependencyResolver.Current.GetService&lt;IService1&gt;();
      ...
  }
  </code></pre>
  
  <p>Also, how it would be in both, non-static and static classes?</p>
  
  <p>Thanks in advance.</p>