1

I have a service that is registered in my container as a single instance

public class MyModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<MyService>()
            .As<IMyService>()
            .SingleInstance();

    }
}

The container is created as below

 public static IContainer SetupContainer()
 {
     var builder = new ContainerBuilder();
     var moduleTypes = TypeCache.GetTypes(x => x.IsClassEx() && !x.IsAbstractEx() && x.ImplementsInterfaceEx<IModule>());

     foreach (var moduleType in moduleTypes)
     {
        if (Activator.CreateInstance(moduleType) is IModule module)
           builder.RegisterModule(module);
     }

     var assemblies = AppDomain.CurrentDomain.GetAssemblies();
     builder.RegisterAssemblyModules(assemblies);

     var result = builder.Build();
     return result;
  }

This all works perfectly within normal code - I can inject my service and its resolved as I expect

However, when I try to inject my service into a web api controller, the service is again resolved, but Autofac gives me a NEW instance of my service

How can I prevent this behaviour so that the originally created instance is injected?

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Paul
  • 2,773
  • 7
  • 41
  • 96

1 Answers1

0

I think that what are you missing here is that you are not actually resolving your container in the right place and so depending on what type of integration you are using you could do one of the following.

//For OWIN you could do something like the following.
public class Startup
{
  public void Configuration(IAppBuilder app)
  {
    var container = YourObject.SetupContainer();

    // Register the Autofac middleware FIRST. This also adds
    // Autofac-injected middleware registered with the container.
    app.UseAutofacMiddleware(container);

    // ...then register your other middleware not registered
    // with Autofac.
  }
}

//In your Global.asax.cs 

    protected void Application_Start() 
    {

       var container = YourObject.SetupContainer();
       DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

    }

MVC Example OWIN Implementation