I am using Unity. I am able to register normal open generic types. But in this case the interface has the open generic nested one step inside.
Is there any way to register this kind of thing with 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>>>();
}
}
Shot answer - it's impossible :) I spent a couple of hours exploring this problem and didn't find a way to tell Unity how to do this.
You need implement another interface:
internal interface IDoSomethingCommandCommandHandler<out T> { }
class DoSomethingCommandHandler<TModel> : ICommandHandler<DoSomethingCommand<TModel>>, IDoSomethingCommandCommandHandler<TModel>
And register by this interface:
container.RegisterType(
typeof(IDoSomethingCommandCommandHandler<>),
typeof(DoSomethingCommandHandler<>));
var res = container.Resolve<IDoSomethingCommandCommandHandler<object>>();
Or explicitly register for every nested type:
var container = new UnityContainer();
container.RegisterType(
typeof(ICommandHandler<>).MakeGenericType(typeof(DoSomethingCommand<object>)),
typeof(DoSomethingCommandHandler<object>));
var res = container.Resolve<ICommandHandler<DoSomethingCommand<object>>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With