My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
AspNetIntegration  
ASP.NET integration provides dependency injection for web forms pages.
Autofac2
Updated Oct 24, 2011 by travis.illig

Types of ASP.NET Applications

In recent versions of ASP.NET you have a few options. Pending on how you choose to construct your site, Autofac offers different integration techniques.

  • ASP.NET Web Forms: In an ASP.NET application, the web forms framework creates pages and controls using reflection in a way that cannot be intercepted for constructor injection to be performed. Property injection is the best available strategy, and Autofac provides the Autofac.Integration.Web library to achieve flexible property injection for ASP.NET pages and user controls.
  • ASP.NET MVC2: Setup for an ASP.NET MVC2 application is almost identical to setup for a web forms application. Where differences or options exist, they will be noted. MVC2-specific additions and notes can be found on the MvcIntegration page.
  • ASP.NET MVC3: Setup for an ASP.NET MVC3 application is slightly different than web forms or MVC2 due to the introduction of DependencyResolver. See the Mvc3Integration page for details on MVC3 application setup.
  • Mixed Web Forms and MVC: If you're running an application that has both web forms and MVC, you'll need to pay attention to both the Web Forms instructions and MVC instructions. The two can happily coexist in the same application.

Standard Integration

In order to integrate Autofac with ASP.NET in the most common fashion, you'll need to...

Once you've done those things, a standard ASP.NET web forms application will be ready to go. If you're using ASP.NET MVC2 you still need to do all of this, but there are a few additional steps.

Reference Assemblies

Add references from your ASP.NET application to the following assemblies...

  • Autofac.dll
  • Autofac.Integration.Web.dll

If you are using ASP.NET MVC2, you'll also need to reference Autofac.Integration.Web.Mvc.dll.

Add Modules to Web.config

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 -->
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
      <add
        name="PropertyInjection"
        type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <!-- This section is used for IIS7 -->
    <modules>
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"
        preCondition="managedHandler"/>
      <add
        name="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 ("Cassini") uses the IIS6 settings even if your target deployment environment is IIS7.

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 UnsetPropertyInjection module is also provided which will only set properties on web forms/controls that have null values.)

For ASP.NET MVC2 the PropertyInjectionModule is optional. While it won't hurt to have it there, ASP.NET MVC hooks up in a different way (see MvcIntegration) so in a pure MVC site this won't get you property injection. That said, if you have a web forms site (or an MVC/web forms mix) then you need to have the PropertyInjectionModule in place.

Implement IContainerProviderAccessor in Global.asax

The dependency injection modules expect that the HttpApplication instance supports IContainerProviderAccessor. A complete global application class is shown below:

public class Global : HttpApplication, IContainerProviderAccessor
{
  // Provider that holds the application container.
  static IContainerProvider _containerProvider;

  // Instance property that will be used by Autofac HttpModules
  // to resolve and inject dependencies.
  public IContainerProvider ContainerProvider
  {
    get { return _containerProvider; }
  }

  protected void Application_Start(object sender, EventArgs e)
  {
    // Build up your application container and register your dependencies.
    var builder = new ContainerBuilder();
    builder.RegisterType<SomeDependency>();
    // ... continue registering dependencies...

    // Once you're done registering things, set the container
    // provider up with your registrations.
    _containerProvider = new ContainerProvider(builder.Build());
  }
}

Autofac.Integration.Web.IContainerProvider exposes two useful properties: ApplicationContainer and RequestLifetime.

  • 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.

Web Forms Integration Complete

For a web forms application, the above steps are all you need to do. The rest of this document will explain some additional/advanced usage scenarios.

If you're using ASP.NET MVC2 there are a few additional integration steps.

Component Lifetimes

When you register components for injection, you have the standard set of instance scopes to work with: per dependency, single instance, or per lifetime scope.

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 "HttpRequestScoped()" extension method in the Autofac.Integration.Web namespace:

var builder = new ContainerBuilder();
builder.RegisterType<Foo>().As<IFoo>().HttpRequestScoped();

Manual Dependency Resolution

In some cases, like in programmatic creation of user controls or other objects, you may need to manually inject properties on an object. To do this, you need to:

  • Get the current application instance.
  • Cast it to Autofac.Integration.Web.IContainerProviderAccessor.
  • Get the container provider from the application instance.
  • Get the request lifetime from the container provider and use the InjectProperties method to inject the properties on the object.

In code, that looks like this:

var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
cp.RequestLifetime.InjectProperties(objectToSet);

Web Forms Tips and Tricks

There are some specific techniques and tips you can take advantage of when working with ASP.NET web forms. For MVC2 tips, see the ASP.NET MVC2 integration page.

Implementing Web Forms Pages and User Controls

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 (as seen earlier) to populate those properties for you.

Be sure to register the dependencies you'll need at application startup (as seen in the IContainerProviderAccessor implementation above)...

var builder = new ContainerBuilder();
builder.RegisterType<Foo>().As<IFoo>().HttpRequestScoped();
// ... continue registering dependencies and then build the
// container provider...
_containerProvider = new ContainerProvider(builder.Build());

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

// MyPage.aspx.cs
public partial class MyPage : Page
{
  // This property will be set for you by the PropertyInjectionModule.
  public IFoo SomeDependency { get; set; }

  protected void Page_Load(object sender, EventArgs e)
  {
    // Now you can use the property that was set for you.
    label1.Text = this.SomeDependency.SomeMessage;
  }
}

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 dependencies manually resolved.

Explicit Injection via Attributes

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 attribute 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 -->
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
      <add
        name="AttributedInjection"
        type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <!-- This section is used for IIS7 -->
    <modules>
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"
        preCondition="managedHandler"/>
      <add
        name="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]
public partial class MyPage : Page
{
  // This property will be set for you by the AttributedInjectionModule.
  public IFoo SomeDependency { get; set; }

  // ...use the property later as needed.
}

Dependency Injection via Base Page Class

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 dependency resolution 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.

protected void Page_PreInit(object sender, EventArgs e)
{
  var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
  var cp = cpa.ContainerProvider;
  cp.RequestLifetime.InjectProperties(this);
}

Creating a Custom Dependency Injection Models

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.

There is one abstract member to implement:

protected abstract IInjectionBehaviour GetInjectionBehaviourForHandlerType(Type handlerType);

The returned IInjectionBehaviour can be one of the predefined NoInjection, PropertyInjection or UnsetPropertyInjection properties, or a custom implementation of the IInjectionBehaviour interface.

Additional Resources

Building this module was made much easier by this great article over at Geoff Lane's blog.

Comment by michiel...@gmail.com, Oct 25, 2010

I think in version 2.2 HttpRequestScoped? is replaced by InstancePerHttpRequest? which is equivalent to InstancePerLifetimeScope?, is it not? It would be nice if this documentation is updated to refelct these API changes.

Comment by ChrisDRo...@gmail.com, Jun 17, 2011

Looks like the manual dependency injection api has changed. InjectProperties? doesn't exist. What is the proper way now?


Sign in to add a comment
Powered by Google Project Hosting