To get Autofac integrated with web forms you need to reference the web forms integration NuGet package, add the modules to web.config, and implement IContainerProviderAccessor on your Global application class.

Add the modules to web.config:

<configuration><system.web><httpModules><!-- This section is used for IIS6 --><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/><addname="PropertyInjection"type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/></httpModules></system.web><system.webServer><!-- This section is used for IIS7 --><modules><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"preCondition="managedHandler"/><addname="PropertyInjection"type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"preCondition="managedHandler"/></modules></system.webServer></configuration>

Implement IContainerProviderAccessor:

publicclassGlobal:HttpApplication,IContainerProviderAccessor{// Provider that holds the application container.staticIContainerProvider_containerProvider;// Instance property that will be used by Autofac HttpModules// to resolve and inject dependencies.publicIContainerProviderContainerProvider{get{return_containerProvider;}}protectedvoidApplication_Start(objectsender,EventArgse){// Build up your application container and register your dependencies.varbuilder=newContainerBuilder();builder.RegisterType<SomeDependency>();// ... continue registering dependencies...// Once you're done registering things, set the container// provider up with your registrations._containerProvider=newContainerProvider(builder.Build());}}

The sections below go into further detail about what each of these features do and how to use them.

The way that Autofac manages component lifetimes and adds dependency injection into the ASP.NET pipeline is through the use of IHttpModule implementations. You need to configure these modules in web.config.

The following snippet config shows the modules configured.

<configuration><system.web><httpModules><!-- This section is used for IIS6 --><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/><addname="PropertyInjection"type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/></httpModules></system.web><system.webServer><!-- This section is used for IIS7 --><modules><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"preCondition="managedHandler"/><addname="PropertyInjection"type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"preCondition="managedHandler"/></modules></system.webServer></configuration>

Note that while there are two different sections the modules appear in - one each for IIS6 and IIS7 - it is recommended that you have both in place. The ASP.NET Developer Server uses the IIS6 settings even if your target deployment environment is IIS7. If you use IIS Express it will use the IIS7 settings.

The modules you see there do some interesting things:

The ContainerDisposalModule lets Autofac dispose of any components created during request processing as soon as the request completes.

The PropertyInjectionModule injects dependencies into pages before the page lifecycle executes. An alternative UnsetPropertyInjectionModule is also provided which will only set properties on web forms/controls that have null values. (Use only one or the other, but not both.)

publicclassGlobal:HttpApplication,IContainerProviderAccessor{// Provider that holds the application container.staticIContainerProvider_containerProvider;// Instance property that will be used by Autofac HttpModules// to resolve and inject dependencies.publicIContainerProviderContainerProvider{get{return_containerProvider;}}protectedvoidApplication_Start(objectsender,EventArgse){// Build up your application container and register your dependencies.varbuilder=newContainerBuilder();builder.RegisterType<SomeDependency>();// ... continue registering dependencies...// Once you're done registering things, set the container// provider up with your registrations._containerProvider=newContainerProvider(builder.Build());}}

ApplicationContainer is the root container that was built at application start-up.

RequestLifetime is a component lifetime scope based on the application container that will be disposed of at the end of the current web request. It can be used whenever manual dependency resolution/service lookup is required. The components that it contains (apart from any singletons) will be specific to the current request (this is where per-request lifetime dependencies are resolved).

In order to inject dependencies into web forms pages (System.Web.UI.Page instances) or user controls (System.Web.UI.UserControl instances) you must expose their dependencies as public properties that allow setting. This enables the PropertyInjectionModule to populate those properties for you.

Be sure to register the dependencies you’ll need at application startup.

Then in your page codebehind, create public get/set properties for the dependencies you’ll need:

// MyPage.aspx.cspublicpartialclassMyPage:Page{// This property will be set for you by the PropertyInjectionModule.publicIServiceMyService{get;set;}protectedvoidPage_Load(objectsender,EventArgse){// Now you can use the property that was set for you.label1.Text=this.MyService.GetMessage();}}

This same process of public property injection will work for user controls, too - just register the components at application startup and provide public get/set properties for the dependencies.

It is important to note in the case of user controls that properties will only be automatically injected if the control is created and added to the page’s Controls collection by the PreLoad step of the page request lifecycle. Controls created dynamically either in code or through templates like the Repeater will not be visible at this point and must have their properties manually injected.

When adding dependency injection to an existing application, it is sometimes desirable to distinguish between web forms pages that will have their dependencies injected and those that will not. The InjectPropertiesAttribute in Autofac.Integration.Web, coupled with the AttributedInjectionModule help to achieve this.

If you choose to use the AttributedInjectionModule, no dependencies will be automatically injected into public properties unless they’re marked with a special attribute.

First, remove the PropertyInjectionModule from your web.config file and replace it with the AttributedInjectionModule:

<configuration><system.web><httpModules><!-- This section is used for IIS6 --><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/><addname="AttributedInjection"type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web"/></httpModules></system.web><system.webServer><!-- This section is used for IIS7 --><modules><addname="ContainerDisposal"type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"preCondition="managedHandler"/><addname="AttributedInjection"type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web"preCondition="managedHandler"/></modules></system.webServer></configuration>

Once this is in place, pages and controls will not have their dependencies injected by default. Instead, they must be marked with the Autofac.Integration.Web.Forms.InjectPropertiesAttribute or Autofac.Integration.Web.Forms.InjectUnsetPropertiesAttribute. The difference:

InjectPropertiesAttribute will always set public properties on the page/control if there are associated components registered with Autofac.

InjectUnsetPropertiesAttribute will only set the public properties on the page/control if they are null and the associated components are registered.

[InjectProperties]publicpartialclassMyPage:Page{// This property will be set for you by the AttributedInjectionModule.publicIServiceMyService{get;set;}// ...use the property later as needed.}

If you would rather not automatically inject properties using a module (e.g., the AttributedInjectionModule or PropertyInjectionModule as mentioned earlier), you can integrate Autofac in a more manual manner by creating a base page class that does manual property injection during the PreInit phase of the page request lifecycle.

This option allows you to derive pages that require dependency injection from a common base page class. Doing this may be desirable if you have only a very few pages that require dependency injection and you don’t want the AttributedInjectionModule in the pipeline. (You still need the ContainerDisposalModule.) If you have more than a small few pages it may be beneficial to consider explicit injection via attributes.

If the provided Property, Unset Property, and Attributed dependency injection models are unsuitable, it is very easy to create a custom injection behavior. Simply subclass Autofac.Integration.Web.DependencyInjectionModule and use the result in Web.config.