Skip to content

Instantly share code, notes, and snippets.

@jamesbascle
Last active March 31, 2016 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbascle/0c06c5f5f43e94f88b8db4d9bbb80e03 to your computer and use it in GitHub Desktop.
Save jamesbascle/0c06c5f5f43e94f88b8db4d9bbb80e03 to your computer and use it in GitHub Desktop.
MIT License
Copyright (c) 2016 James Bascle
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using Autofac;
namespace AttributeIocExample
{
class Program
{
static void Main(string[] args)
{
//create container
var cb = new ContainerBuilder();
cb.RegisterType<ConstructedByContainer>().AsSelf();
var container = cb.Build();
//Magic happens here
AutoImplementFactoryFuncs(container);
//create filter and execute normal filter method
var filter = new ExampleFilterAttribute();
filter.OnActionExecuted(null);
Console.Read();
}
private static void AutoImplementFactoryFuncs(IContainer container)
{
//find all static properties tagged with "AutoImpl" attribute that are of type Func<T>
var factoryFuncsToAutoImplement =
AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(c => c.DefinedTypes)
.SelectMany(c => c.GetProperties(BindingFlags.Public | BindingFlags.Static))
.Where(e => e.CustomAttributes.Any(a => a.AttributeType == typeof(AutoImplAttribute)))
.Where(
p =>
p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof(Func<>))
.ToList();
//get a MethodInfo for the AutoFac resolve method
var resolveMethod = typeof(ResolutionExtensions).GetMethod("Resolve", new[] { typeof(IComponentContext), typeof(Type) });
foreach (var prop in factoryFuncsToAutoImplement)
{
//find the type that the factory function actually needs to create
var typeForFactoryToCreate = prop.PropertyType.GenericTypeArguments[0];
//create an expression that will call the resolve method on the correct container with the correct ServiceType
var methodInvoke = Expression.Call(null, resolveMethod, Expression.Constant(container), Expression.Constant(typeForFactoryToCreate));
//convert the output of the method invokation to the asked for type, and populate the body of the lambda
var f = Expression.Lambda(Expression.Convert(methodInvoke, typeForFactoryToCreate));
//set the newly created lambda to the expression on the AutoImpl'd property
prop.SetValue(null, f.Compile());
}
}
}
[AttributeUsage(AttributeTargets.Property)]
public class AutoImplAttribute : Attribute
{
}
public class ExampleFilterAttribute : ActionFilterAttribute
{
private ConstructedByContainer _cbc;
[AutoImpl]
public static Func<ConstructedByContainer> ConstructedByContainerFactoryFunc { get; set; }
public ExampleFilterAttribute()
{
_cbc = ConstructedByContainerFactoryFunc();
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
_cbc.Proof();
}
}
public class ConstructedByContainer
{
public void Proof() => Console.WriteLine("It works!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment