Autofac SingleInstance not working

孤人 提交于 2019-12-10 15:49:46

问题


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?


回答1:


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




回答2:


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!




回答3:


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.



来源:https://stackoverflow.com/questions/10543363/autofac-singleinstance-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!