简体   繁体   English

向Unity注册通用处理程序接口

[英]Registering Generic Handler Interface with Unity

I've looked at multiple threads regarding registering generic interfaces in Unity, unfortunately I've not managed to get any of them to actually work. 我看过多个关于在Unity中注册通用接口的线程,不幸的是,我没有设法使它们中的任何一个都能正常工作。 This is the interface that is defined. 这是定义的接口。

public interface IHandler<in TCommand>{}

Example class: 示例类:

public class MyTestHandler : IHandler<TestCommand>
{}

I'm then trying to resolve them in a factory: 然后,我试图在工厂中解决它们:

    public IHandler<TCommand> Create<TCommand>()
    {
        return _container.Resolve<IHandler<TCommand>>();
    }

I've attempted to register my Handler as follows: 我尝试注册我的处理程序,如下所示:

container.RegisterTypes(AllClasses.FromLoadedAssemblies().Where(type => typeof(IHandler<>).IsAssignableFrom(type)), WithMappings.FromAllInterfaces, WithName.TypeName, WithLifetime.Transient);

Unfortunately unless I explicitly register a concrete handler I can't seem to get it to work. 不幸的是,除非我明确注册一个具体的处理程序,否则我似乎无法使其正常工作。 Any suggestions would be great. 任何建议都很好。

Thanks in advance. 提前致谢。

The problem's the Where condition: IHandler<> is not assignable from MyTestHandler and therfore you get no registrations. 问题是Where条件:无法从MyTestHandler分配IHandler<>因此无法获得注册。

This works fine for me, that is, instance receives a MyTestHandler and instance2 receives a MyTestHandler2 : 这对我来说很好用,即instance接收MyTestHandlerinstance2接收MyTestHandler2

internal class Program
{
    static void Main( string[] args )
    {
        var container = new UnityContainer();

        container.RegisterTypes( AllClasses.FromLoadedAssemblies().Where( type => type.Name.Contains("Handler") ), WithMappings.FromAllInterfaces, WithName.Default, WithLifetime.Transient );
        var instance = container.Resolve<IHandler<TestCommand>>();
        var instance2 = container.Resolve<IHandler<TestCommand2>>();
    }
}

public interface IHandler<TCommand>
{
}

public class MyTestHandler : IHandler<TestCommand>
{
}

public class TestCommand
{
}
public class MyTestHandler2 : IHandler<TestCommand2>
{
}

public class TestCommand2
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM