假设我有以下内容:
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/