强类型Unity配置

时间:2014-05-11 10:19:53

标签: c# unity-container

我最近使用Unity作为IOC。虽然我并没有真正将它用作依赖注入器,但我将它用作工厂。

现在,在我的代码中,我使用以下命令注册类型:

container.RegisterType<IFooInterface, FooClass>(
            new[] { new InjectionProperty("SomeProperty", "SomeValue") });

有没有办法在属性注入中使用强类型?

1 个答案:

答案 0 :(得分:3)

您可以使用流畅的API来完成。

public static class ContainerExtensions
{

    public static InjectionBuilder<TFrom, TTo> BuildInjections<TFrom, TTo>(this IUnityContainer container)
        where TTo : TFrom
    {
        return new InjectionBuilder<TFrom, TTo>(container);
    }

    public static MemberInfo GetMemberInfo(this Expression expression)
    {
        var lambda = (LambdaExpression)expression;

        MemberExpression memberExpression;
        if (lambda.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)lambda.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else
            memberExpression = (MemberExpression)lambda.Body;

        return memberExpression.Member;
    }
}

// This class is the fluent API
public class InjectionBuilder<TFrom, TTo>
    where TTo : TFrom
{
    private readonly IList<InjectionMember> _injectionMembers = new List<InjectionMember>();
    private readonly IUnityContainer _container;
    public InjectionBuilder(IUnityContainer unityContainer)
    {
        _container = unityContainer;
    }

    public InjectionBuilder<TFrom, TTo> AddPropertyInjection<TType>(Expression<Func<TFrom, TType>> property,
                                                                    TType value)
    {
        var propName = property.GetMemberInfo().Name;
        _injectionMembers.Add(new InjectionProperty(propName, value));
        return this;
    }

    public IUnityContainer Register()
    {
        return _container.RegisterType<TFrom, TTo>(_injectionMembers.ToArray());
    }

}

然后像

一样使用它
        IUnityContainer container; // already Init
        container.BuildInjections<IFooInterface, FooClass>()
                 .AddPropertyInjection(f => f.SomeProperty, "SomeValue")
                 .Register();

您可以获得类型安全性,并且可以继续添加PropertyInjections,直到您调用Register。您还可以扩展该类以注册您想要的任何其他统一注入工厂。