Skip to content

Instantly share code, notes, and snippets.

@ducas
Created July 4, 2012 00:15
Show Gist options
  • Save ducas/3044309 to your computer and use it in GitHub Desktop.
Save ducas/3044309 to your computer and use it in GitHub Desktop.
Auto-Registering Types
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Builder;
using Autofac.Integration.Mvc;
using Web.Registration;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.AutofacMvc), "Start")]
namespace Web.App_Start
{
public static class AutofacMvc
{
public static void Start()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterAssemblyModules();
builder.RegisterAutos();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
private static void RegisterAutos(this ContainerBuilder builder)
{
var registered = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => t.GetCustomAttributes().Any(a => a.GetType() == typeof (AutoRegisterAttribute)));
foreach (var type in registered)
{
var attribute = type.GetCustomAttribute<AutoRegisterAttribute>();
builder.RegisterType(type).WithScope(attribute.Scope).AsImplementedInterfaces();
}
}
private static IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> WithScope(this IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> builder, Scope scope)
{
switch (scope)
{
case Scope.Singleton:
return builder.SingleInstance();
case Scope.Request:
return builder.InstancePerHttpRequest();
}
return builder;
}
}
}
using System;
namespace Web.Registration
{
public class AutoRegisterAttribute : Attribute
{
public Scope Scope { get; set; }
public AutoRegisterAttribute()
{
Scope = Scope.Dependecy;
}
}
public enum Scope
{
Dependecy,
Request,
Singleton
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment