4

I have an application that dynamically starts different processes. Each one of that processes consumes an autofac CoreModule, and each one has his own Module for that very process.

CoreModule defines a few components that must be SingleInstance across all the processes of the application.

For example let's say I have registered:

builder.RegisterType<AcrossComponent>().As<IAcrossComponent>().SingleInstance();

The thing is that on every Bootstrapper that registers CoreModule, they create one instance of AcrossComponent that is SingleInstance on that very IContainer.

I managed to solve it by using AcrossComponent as a facade of a book singleton

namespace Sample
{
  public class AcrossComponent : IAcrossComponent
  {
    public AcrossComponent()
    {
    }

    public void DoSomething()
    {
        RealAcrossComponent.Instance.DoSomething();
    }
  }

  private class RealAcrossComponent
  {
    private static RealAcrossComponent _instance;
    public static RealAcrossComponent Instance
    {
        get
        {
            if(_instance == null)
                _instance = new RealAcrossComponent();

            return _instance;
        }
    }

    private RealAcrossComponent()
    {
    }

    public void DoSomething()
    {}
  }
}

Of course this is not the way I'd like to solve this need, Autofac probably solves it in anyway I could not find.

(Already tried by registering same instance of CoreModule, but it seems it changes nothing, its just a facade for the registrations)

Thanks in advance!

Edit 1:

The application is a Windows Form, where user configure stuff, and contains multiple buttons, each one hits the entry point:

public static class BackGroundProcess1{
 public static void StartBackground()
 {
  //creates container with CoreModule, BackGround1Module and starts everything.
   _container.Resolve<IMainComponent>().StartBackground();
 }
}

There are 4 classes like that, that acts like an entry point for all the things that start processing in background. I would like all those 4 to share the CoreModule instances.

  • Why can't you just register the singleton once at the root of the whole application? Can you elaborate a bit on how the app is composed? – Ant P Aug 01 '15 at 15:11
  • You lost me at "multiple containers". Most applications should only contain one. And your question underlines why. – NightOwl888 Aug 03 '15 at 21:29
  • CoreModule components consumes different implementations of some components, the implementation is defined in one of 4 other possible Modules. Let's say I refactor and use 1 container, how do I load a different module depending on the entry point? – Martin Solovey Aug 04 '15 at 17:07
  • I had this same problem and was able to solve it by using `RegisterInstance` https://autofaccn.readthedocs.io/en/latest/register/registration.html#instance-components – Kelvin Apr 23 '20 at 02:45

0 Answers0