Autofac PropertiesAutowired - Is it possible to ignore a one or more properties?

只谈情不闲聊 提交于 2020-01-01 07:15:27

问题


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?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/21606629/autofac-propertiesautowired-is-it-possible-to-ignore-a-one-or-more-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!