Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample Global.asax for a webforms project
// You could use a module to describe all the dependenices in some api dll and make
// it easier to load all components from that project.
public class ApiModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register<UserManager>().As<IUserManager>();
builder.Register<QasAddressService>().As<IAddressSearchService>();
// Anything else required.
}
}
// Sample global asax that creates a container for the web application. It creates
// a container via the 'container builder' and components are registered in it
// directly or by 'modules' that bring common dependencies together.
public class Global : HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
private 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.
ContainerBuilder builder = new ContainerBuilder();
// Register a type directly. This is a basic registration that doesn't
// control lifetime or whether the component is 'IDisposable'.
builder.RegisterType<SomeDependency>().As<ISomeInterface>();
// Structure some dependencies in a wrapping 'module'. See the module code
// for a motivation for this.
builder.RegisterModule<ApiModule>();
// Once you're done registering things, set the container
// provider up with your registrations.
containerProvider = new ContainerProvider(builder.Build());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment