2

Despite the advice to pass dependencies through the constructor I've found that the development cost of having parameterless constructors and then autowiring all of the properties on everything is significantly less and makes the application much easier to develop out and maintain. However sometimes (on a view model for example) I have a property that is registered with the container, but that I don't want to populate at construction (for example the selected item bound to a container).

Is there any way to tell the container to ignore certain properties when it autowires the rest?

At the moment I'm just resetting the properties marked with an attribute in the on activated event a la:

public static IRegistrationBuilder<TLimit, ScanningActivatorData, TRegistrationStyle> 
    PropertiesAutowiredExtended<TLimit, TRegistrationStyle>(
    this IRegistrationBuilder<TLimit, ScanningActivatorData, TRegistrationStyle> builder)
{
    builder.ActivatorData.ConfigurationActions.Add(
        (type, innerBuilder) =>
        {
            var parameter = Expression.Parameter(typeof(object));
            var cast = Expression.Convert(parameter, type);
            var assignments = type.GetProperties()
                .Where(candidate => candidate.HasAttribute<NotAutowiredAttribute>())
                .Select(property => new { Property = property, Expression = Expression.Property(cast, property) })
                .Select(data => Expression.Assign(data.Expression, Expression.Default(data.Property.PropertyType)))
                .Cast<Expression>()
                .ToArray();

            if (assignments.Any())
            {
                var @action = Expression
                    .Lambda<Action<object>>(Expression.Block(assignments), parameter)
                    .Compile();

                innerBuilder.OnActivated(e =>
                {
                    e.Context.InjectUnsetProperties(e.Instance);
                    @action(e.Instance);
                });
            }
            else
            {
                innerBuilder.OnActivated(e => e.Context.InjectUnsetProperties(e.Instance));
            }
        });

    return builder;
}

Is there a better way to do this?

satnhak
  • 9,407
  • 5
  • 63
  • 81

1 Answers1

2

Not sure that this is a better one, but you can go from another side, register only needed properties via WithProperty syntax. Pros is that Autofac doesn't resolve unnecessary services. Here's a working example:

public class MyClass
{
    public MyDependency MyDependency { get; set; }
    public MyDependency MyExcludeDependency { get; set; }
}
public class MyDependency {}

public class Program
{
    public static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MyDependency>();
        builder.RegisterType<MyClass>().WithPropertiesAutowiredExcept("MyExcludeDependency");

        using (var container = builder.Build())
        {
            var myClass = container.Resolve<MyClass>();

            Console.WriteLine(myClass.MyDependency == null);
            Console.WriteLine(myClass.MyExcludeDependency == null);
        }
    }
}

public static class PropertiesAutowiredExtensions
{
    // Extension that registers only needed properties
    // Filters by property name for simplicity
    public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TRegistrationStyle>
        WithPropertiesAutowiredExcept<TLimit, TReflectionActivatorData, TRegistrationStyle>(
        this IRegistrationBuilder<TLimit, TReflectionActivatorData, TRegistrationStyle> registrationBuilder,
        params string[] propertiesNames)
        where TReflectionActivatorData : ReflectionActivatorData
    {
        var type = ((IServiceWithType)registrationBuilder.RegistrationData.Services.Single()).ServiceType;

        foreach (var property in type
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(pi => pi.CanWrite && !propertiesNames.Contains(pi.Name)))
        {
            // There's no additional checks like in PropertiesAutowired for simplicity
            // You can add them from Autofac.Core.Activators.Reflection.AutowiringPropertyInjector.InjectProperties

            var localProperty = property;
            registrationBuilder.WithProperty(
                new ResolvedParameter(
                    (pi, c) =>
                        {
                            PropertyInfo prop;
                            return pi.TryGetDeclaringProperty(out prop) &&
                                   prop.Name == localProperty.Name;
                        },
                    (pi, c) => c.Resolve(localProperty.PropertyType)));
        }

        return registrationBuilder;
    }

    // From Autofac.Util.ReflectionExtensions
    public static bool TryGetDeclaringProperty(this ParameterInfo pi, out PropertyInfo prop)
    {
        var mi = pi.Member as MethodInfo;
        if (mi != null && mi.IsSpecialName && mi.Name.StartsWith("set_", StringComparison.Ordinal)
            && mi.DeclaringType != null)
        {
            prop = mi.DeclaringType.GetProperty(mi.Name.Substring(4));
            return true;
        }

        prop = null;
        return false;
    }
}
Alexandr Nikitin
  • 7,258
  • 2
  • 34
  • 42
  • Thanks, I think you are right I should start from the other end and roll my own autowirer rather than fudging out the work that the container has already done. – satnhak Feb 06 '14 at 22:49
  • @TheMouthofaCow Right. Or even contribute to the project and introduce a predicate into Autofac.Core.Activators.Reflection.AutowiringPropertyInjector.InjectProperties which could give a pretty good extension point. – Alexandr Nikitin Feb 07 '14 at 06:24
  • Yes I'd be more than happy to I'll see if I can get some time over the weekend. – satnhak Feb 07 '14 at 06:52
  • Not quite a fork, but here is a gist: https://gist.github.com/bandwidthjunkie/8956071 – satnhak Feb 12 '14 at 14:03