简体   繁体   中英

Injection in web api controller not using Single Instance

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM