1

I'm having an issue with the lifetime scope of autofac lasting across a request in an asp.net webforms site.

I'm register a factory in auto fac thus:

builder.RegisterType<DoSomethingFactory>().As<IDoSomethingFactory>().InstancePerLifetimeScope();

This occurs in the app_start of course.

then I have a simple user control that calls a method of this factory

IDoSomethingFactory doSomethingFactory = Resolver.Resolve<IDoSomethingFactory>();
Number.Text = doSomethingFactory.DoSomething().ToString();

I have two instances of this control on a page, so that the DoSomething method should be called twice and the factory should be resolved twice also.

The first time I run the site, the contstructor for the DoSomethingFactory is fired, and there are 2 subsequent calls to the DoSomething method. The second request, results in 2 calls to the DoSomething method without a fresh new-ing up of the factory.

If I take out the InstancePerLifetimeScope on the registering then the factory is instantiated on each resolve. Most answers I have seen for this talk about an MVC site. I also have an MVC site and am using it in the same manner and it is working as requested, hence the need to question for asp.net webforms

To be clear I would like the factory to be instantiated once every request. Any help or ideas would be welcome.

Many thanks

Will

wdhough
  • 155
  • 3
  • 12

1 Answers1

2

If you want to have one instance of your DoSomethingFactory per request you need to use the InstancePerHttpRequest extension method.

From the Autofac wiki: WebFormsIntegration

ASP.NET integration adds a special component lifetime that allows a component instance to live for the life of a single HTTP request. You can register components using the InstancePerHttpRequest() extension method in the Autofac.Integration.Web namespace.

So change your registration to:

builder.RegisterType<DoSomethingFactory>()
       .As<IDoSomethingFactory>()
       .InstancePerHttpRequest();
nemesv
  • 138,284
  • 16
  • 416
  • 359