Bailey Ling's Memeber Injection Attribute

23 views
Skip to first unread message

Adam Hill

unread,
Sep 22, 2015, 3:50:04 PM9/22/15
to Autofac
Has anyone / can anyone, port Bailey Ling's Memeber Injection Attribute - http://bling.github.io/blog/2009/09/07/member-injection-module-for-autofac/ to the current verson of Autofac?

The Module API has changed significantly enough that I have no idea where to begin.

Thanks.

Kaleb Pederson

unread,
Sep 22, 2015, 4:33:09 PM9/22/15
to aut...@googlegroups.com
VPN has been down today for me... so you're in luck, assuming I understand your request:

Here's the code:

public class MemberInjectionModule : Module
{
protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
{
registration.Activated += OnComponentActivated;
}

private void OnComponentActivated(object sender, ActivatedEventArgs<object> e)
{
const BindingFlags flags = BindingFlags.Instance |
  BindingFlags.NonPublic |
  BindingFlags.Public;
var type = e.Instance.GetType();
foreach (var field in type.GetFields(flags))
{
if (field.GetCustomAttributes(typeof(InjectedAttribute), true).Length > 0)
field.SetValue(e.Instance, e.Context.Resolve(field.FieldType));
}
foreach (var prop in type.GetProperties(flags))
{
if (prop.GetCustomAttributes(typeof(InjectedAttribute), true).Length > 0)
{
if (prop.GetIndexParameters().Length > 0)
throw new InvalidOperationException("Indexed properties cannot be injected.");

prop.SetValue(e.Instance, e.Context.Resolve(prop.PropertyType), null);
}
}
}
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class InjectedAttribute : Attribute { }

And here's a simple unit test:

public class SampleClass
{
[Injected]
public IOther InjectedOther { get; set; }

public IOther NotInjectedOther { get; set; }
}

[Test]
public void MemberInjectionModule_checks_InjectedAttribute_and_injects_dependency()
{
var builder = new ContainerBuilder();
builder.RegisterModule<MemberInjectionModule>();
builder.RegisterType<Other1>().As<IOther>();
builder.RegisterType<SampleClass>();
var container = builder.Build();
var resolved = container.Resolve<SampleClass>();
Assert.That(resolved.InjectedOther, Is.Not.Null);
Assert.That(resolved.NotInjectedOther, Is.Null);
}



--
You received this message because you are subscribed to the Google Groups "Autofac" group.
To unsubscribe from this group and stop receiving emails from it, send an email to autofac+u...@googlegroups.com.
To post to this group, send email to aut...@googlegroups.com.
Visit this group at http://groups.google.com/group/autofac.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages