在 Unity 中注册嵌套的开放泛型类型
本文关键字:泛型类型 嵌套 Unity 注册 | 更新日期: 2023-09-27 18:37:08
我正在使用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>>>();
}
}
射击答案 - 这是不可能的:)我花了几个小时来探索这个问题,但没有找到告诉 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>>>();