Created
July 4, 2012 00:15
-
-
Save ducas/3044309 to your computer and use it in GitHub Desktop.
Auto-Registering Types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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