How to do open generic decorator chaining with unity + UnityAutoRegistration

后端 未结 2 550
遇见更好的自我
遇见更好的自我 2020-12-10 09:08

Went off on an interesting tangent today after reading this article on command handler decoration. I wanted to see if I could implement the pattern using Unity instead of Si

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 09:42

    This would be the equivalent in Unity:

    // Go look in all assemblies and register all implementa-
    // tions of ICommandHandler by their closed interface:
    var container = new UnityContainer();
    
    var handlerRegistrations =
        from assembly in AppDomain.CurrentDomain.GetAssemblies()
        from implementation in assembly.GetExportedTypes()
        where !implementation.IsAbstract
        where !implementation.ContainsGenericParameters
        let services =
            from iface in implementation.GetInterfaces()
            where iface.IsGenericType
            where iface.GetGenericTypeDefinition() == 
                typeof(ICommandHandler<>)
            select iface
        from service in services
        select new { service, implementation };
    
    foreach (var registration in handlerRegistrations)
    {
        container.RegisterType(registration.service, 
            registration.implementation, "Inner1");
    }
    
    // Decorate each returned ICommandHandler object with an
    // TransactionCommandHandlerDecorator.
    container.RegisterType(typeof(ICommandHandler<>), 
        typeof(TransactionCommandHandlerDecorator<>),
        "Inner2",
        InjectionConstructor(new ResolvedParameter(
            typeof(ICommandHandler<>), "Inner1")));
    
    // Decorate each returned ICommandHandler object with an
    // DeadlockRetryCommandHandlerDecorator.
    container.RegisterType(typeof(ICommandHandler<>), 
        typeof(DeadlockRetryCommandHandlerDecorator<>), 
        InjectionConstructor(new ResolvedParameter(
            typeof(ICommandHandler<>), "Inner2")));
    

提交回复
热议问题