我正在使用Unity。我可以注册常规的开放泛型类型。但在这种情况下,接口内部有一个开放的通用嵌套步骤。
有没有办法在Unity注册这类东西?
class DoSomethingCommandHandler<TModel> : ICommandHandler<DoSomethingCommand<TModel>>
{
public void Handle(DoSomethingCommand<TModel> cmd)
{
var model = cmd.Model;
//do thing with model
}
}
class QuickTest
{
static void Go()
{
var container = new UnityContainer();
container.RegisterType(
typeof(ICommandHandler<>).MakeGenericType(typeof(DoSomethingCommand<>)),
typeof(DoSomethingCommandHandler<>));
//This blows up:
var res = container.Resolve<ICommandHandler<DoSomethingCommand<object>>>();
}
}
答案 0 :(得分:2)
拍摄答案 - 这是不可能的:) 我花了几个小时探索这个问题,但没有办法告诉Unity如何做到这一点。
您需要实现另一个界面:
internal interface IDoSomethingCommandCommandHandler<out T> { }
class DoSomethingCommandHandler<TModel> : ICommandHandler<DoSomethingCommand<TModel>>, IDoSomethingCommandCommandHandler<TModel>
通过此界面注册:
container.RegisterType(
typeof(IDoSomethingCommandCommandHandler<>),
typeof(DoSomethingCommandHandler<>));
var res = container.Resolve<IDoSomethingCommandCommandHandler<object>>();
或者显式注册每个嵌套类型:
var container = new UnityContainer();
container.RegisterType(
typeof(ICommandHandler<>).MakeGenericType(typeof(DoSomethingCommand<object>)),
typeof(DoSomethingCommandHandler<object>));
var res = container.Resolve<ICommandHandler<DoSomethingCommand<object>>>();