Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac SingleInstance not working

I am trying to get a Singleton instance working with Autofac. I'm kind of doing a quasi-mvvm type thing with Winforms, just an experiment so don't get to hung up on that. But I am trying you have my model be a single instance with a reference in a command (ICommand here is not the WPF variety):

I have the following setup of a container:

var cb = new ContainerBuilder();
cb.RegisterType<CalculateCommissionCommand>().As<ICommand<TradeEntry>>().SingleInstance();
cb.RegisterType<CalculationsModel>().As<ICalculationsModel>().SingleInstance();
cb.Register(c => new CalculationsView() { Model = c.Resolve<ICalculationsModel>() }).SingleInstance();
cb.Build();

Now the Command takes an ICalculationsModel as a constructor parameter. However, when I set a value in the Model being passed to the Command, that value does not appear within the model that has already been set withing the CalculationsView. It seems that the command and the view are being passed different instances of the CalculationsModel despite the "singleInstance" method being called. Am I missing something? Why is this happening?

like image 274
Bitfiddler Avatar asked May 10 '12 23:05

Bitfiddler


3 Answers

We hit a similar problem today and this seems to be the only post where this question is asked, so I thought I'd share our experience in the hopes it helps someone out. In the end it was something right in front of our eyes and of course they're usually the hardest problems to solve :-).

In our scenario, we were:

  1. Registering a specific implementation of a configuration provider
  2. Auto-registering certain types within an assembly.

Something along these lines:

var cb = new ContainerBuilder();
cb.RegisterType<FileBasedConfigurationProvider>()
    .As<IConfigurationProvider>()
    .SingleInstance();

cb.RegisterAssemblyTypes(typeof(MailProvider).Assembly)
    .Where(t => !t.IsAbstract && t.Name.EndsWith("Provider"))
    .AsImplementedInterfaces(); 

Stupidly, we didn't think about/realise that the FileBasedConfigurationProvider was in the same assembly as the MailProvider, so the second registration call basically overwrote the first one; hence, SingleInstance "wasn't working".

Hope that helps someone else out!

like image 103
gerrod Avatar answered Nov 16 '22 23:11

gerrod


It's not clear from your code how you are storing/using the container. It is likely you have created multiple containers.

like image 30
jlew Avatar answered Nov 16 '22 21:11

jlew


In my case the problem was that the parameter to the method generating the second instance was defined as the class instead of the interface i.e.

SomeMethod(ClassName parameter)

instead of

SomeMethod(**I**ClassName parameter)

Obvious mistake, but took a few minutes to see it.

like image 1
KarenR Avatar answered Nov 16 '22 22:11

KarenR