Search code examples
propertiesautofacinternal

Property Injection with internal setter


I have an existing application that I am modifying to use Autofac Property Injection. It seems regardless of which method I use to register my types with properties, the properties are always null unless they have public setters. With other IoC containers (e.g. Structuremap) it's possible to scope the setter internal and make it available using the InternalsVisibleTo attribute on the assembly. This would seem nice to restrict clients from modifying the assignment.

Is this possible with Autofac? Or is there another approach when working with property injection to keep the assignments secure?

I've tried using reflection with PropertiesAutoWired() as well as resolving .WithParameter() from my WebApi Global.asax - specifying the specific parameter to be set with no success as an internal setter.

[assembly: InternalsVisibleTo("MyWebAPI.dll")]
[assembly: InternalsVisibleTo("Autofac.dll")]
[assembly: InternalsVisibleTo("Autofac.Configuration.dll")]
namespace My.Namespace
{
    public class BaseContext
    {
        public MyPublicClass _dbHelper { get; internal set; }

        public BaseContext()
        {

        }

        protected string DbConnectionString
        {
            get
            {
                return _dbHelper.DbConn; //<-Always null unless setter is public
            }
        }
    }
}

Solution

  • You cannot inject internal setters with autofac, because the AutowiringPropertyInjector class is only looking for public properties (see source).

    However a logic in the AutowiringPropertyInjector is very simple so you can create your own version which does injection for non public properties:

    public static class AutowiringNonPublicPropertyInjector
    {
         public static void InjectProperties(IComponentContext context, 
                object instance, bool overrideSetValues)
         {
              if (context == null)
                  throw new ArgumentNullException("context");
              if (instance == null)
                  throw new ArgumentNullException("instance");
              foreach (
                 PropertyInfo propertyInfo in 
                     //BindingFlags.NonPublic flag added for non public properties
                     instance.GetType().GetProperties(BindingFlags.Instance |
                                                      BindingFlags.Public |
                                                      BindingFlags.NonPublic))
             {
                 Type propertyType = propertyInfo.PropertyType;
                 if ((!propertyType.IsValueType || propertyType.IsEnum) &&
                     (propertyInfo.GetIndexParameters().Length == 0 &&
                         context.IsRegistered(propertyType)))
                 {
                     //Changed to GetAccessors(true) to return non public accessors
                     MethodInfo[] accessors = propertyInfo.GetAccessors(true);
                     if ((accessors.Length != 1 || 
                         !(accessors[0].ReturnType != typeof (void))) &&
                          (overrideSetValues || accessors.Length != 2 ||
                          propertyInfo.GetValue(instance, null) == null))
                     {
                         object obj = context.Resolve(propertyType);
                         propertyInfo.SetValue(instance, obj, null);
                     }
                }
            }
        }
    }
    

    And now you can use this class in the OnActivated event

    var builder = new ContainerBuilder();
    builder.RegisterType<MyPublicClass>();
    builder.RegisterType<BaseContext>()
        .OnActivated(args =>   
              AutowiringNonPublicPropertyInjector
                  .InjectProperties(args.Context, args.Instance, true));
    

    However the above listed solution now injects all kind of properties so even private and protected ones so you may need to extend it with some additional checks to make sure that you will only inject the properties what you would expect.