1

嗨,我正在尝试围绕 Unity 创建一个通用包装器,这将使我能够随时更改 IoC 框架,而无需

public static void RegisterTypes(IDependencyInjectionContainerWrapper container)
    {
        List<Type> types = LoadTypesFromAssemblies();
        foreach (var type in types)
        {
            var interfaceType= type.CustomAttributes
                                 .FirstOrDefault(a => a.AttributeType.Name == typeof(DependencyService).Name)
                                 .ConstructorArguments[0].Value;

            container.RegisterType<type, interfaceType>();
        }
    }

这里发生的事情是我得到了一个列表类型,其中应用了属性 DependencyService。

然后我遍历它,我得到属性的第一个构造函数参数。

然后我试图在容器中注册类型抛出泛型。这就是我遇到问题的地方。

我不知道如何传递我在 RegisterType 方法泛型中拥有的两种类型。就目前而言,我遇到了错误,因为我在泛型中传递了一个变量而不是对象类型

有没有办法解决我的问题?

4

2 回答 2

1

如果依赖容器有一个非泛型方法,调用它:

container.RegisterType(type, interfaceType);

如果它没有非泛型方法,并且您可以修改源代码,我强烈建议提供一个;它使这种事情变得容易得多。通常,使用这样的容器,您的泛型方法最终会调用您的非泛型方法:

public void RegisterType(Type implType, Type ifaceType)
{
    ...
}

public void RegisterType<TImpl, TIface>() where TImpl : TIface
{
    this.RegisterType(typeof(TImpl), typeof(TIface));
}

否则,您将不得不通过反射动态提供泛型参数:

var methodInfo = container.GetType().GetMethod("RegisterType");
var actualMethod = methodInfo.MakeGenericMethod(type, interfaceType);
methodInfo.Invoke(container);

但这既不高效也不特别优雅。

于 2013-09-03T18:25:55.537 回答
0

使用MethodInfo.MakeGenericMethod

于 2013-09-03T18:23:47.980 回答