c# - CaSTLe Windsor 注册的类型不同于类型发现中使用的类型

标签 c# castle-windsor

假设我有以下内容:

public interface IMyInterface<T>
{
}

public interface IMyClass<T>
{
}

public class MyClass<T, T2> : IMyClass<T2>
    where T : IMyInterface<T2>
{
}

foreach(/*var impl in classes_that_implement_IInterface<T>*/)
{
    //register IMyClass<T> as MyClass<typeof(impl), T>
}

例如如果我定义

public class MyImplementation : IMyInterface<string>
{
}

将注册以下内容:

IMyClass<string> as MyClass<MyImplementation, string>

有没有一个巧妙的方法来做到这一点?我想不出如何解决这个问题:/

最佳答案

好吧,我做了这个......但它似乎相当......辱骂?

var container = new WindsorContainer();

container.Register(
    Classes.FromThisAssembly()
        .BasedOn(typeof(IMyInterface<>))
        .Configure(x =>
        {
            var iMyInterfaceImpl = x.Implementation;

            var iMyInterface = iMyInterfaceImpl
                .GetTypeInfo()
                .GetInterfaces()
                .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))
                .Single();

            var iMyInterfaceGenericArg0 = iMyInterface.GetGenericArguments()[0];

            var myClassImpl = typeof(MyClass<,>).MakeGenericType(iMyInterfaceImpl, iMyInterfaceGenericArg0);
            var iMyClass = typeof(IMyClass<>).MakeGenericType(iMyInterfaceGenericArg0);

            container.Register(Component.For(iMyClass).ImplementedBy(myClassImpl));
        })
);


container.Resolve(typeof(IMyClass<string>)); // MyClass<MyImplementation, string>

关于c# - CaSTLe Windsor 注册的类型不同于类型发现中使用的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794382/

相关文章:

asp.net-mvc - 如何使用 CaSTLe.Windsor 通过依赖注入(inject)传递构造函数参数?

nhibernate - NHibernate CaSTLe Facility的延迟加载

c# - Linq查询blob列表,内存占用

c# - 将用C#开发的ActiveX组件导入Delphi 2011?

c# - 使用 ElasticSearch Nest 索引动态对象 - StackOverflow Exception

wcf - 工厂被废弃,不能再使用。 NHibernate设施

asp.net-mvc - 我的 Razor View 的自定义基本页面类型,如何使用城堡温莎 Autowiring 属性?

c# - 在 C# 中处理对象

c# - 在 C# 中计算值的数组(从 Excel 转换公式)

caSTLe-windsor - CaSTLe Windsor - 如何按名称解析?