Results 1 to 2 of 2

Thread: Unity - map a class to what it handles by interface?

Threaded View

  1. #2

    Thread Starter
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148

    Re: Unity - map a class to what it handles by interface?

    I was massively overthinking/overengineering this. Instead of all that effort, I simply add the handler class to the container using the name of the cdefinition class it handles...

    vb.net Code:
    1. Public Shared Function GetNameFromCommandDefinition(ByVal handler As Type) As String
    2.  
    3.         'find out what tyoe the handler handles...
    4.         Dim handlerInterface As Type = handler.GetInterface("ICommandHandler`1", False)
    5.         If (handlerInterface IsNot Nothing) Then
    6.             ' Get the name of the first generic class
    7.             If (handlerInterface.GetGenericArguments.Count > 0) Then
    8.                 Return handlerInterface.GetGenericArguments(0).Name
    9.             End If
    10.         End If
    11.  
    12.         Return handler.Name()
    13.  
    14.  
    15.     End Function

    (This function goes in the initial container registration code e.g. )
    vb.net Code:
    1. Public Shared Sub RegisterTypes(container As IUnityContainer)
    2.  
    3.         Dim interfaceType As Type = Nothing
    4.  
    5.         'Get the interface definition for the generic interface we are looking for
    6.         interfaceType = GetType(ICommandHandler(Of ))
    7.  
    8.         container.RegisterTypes(AllClasses.FromAssembliesInBasePath(includeUnityAssemblies:=False, includeSystemAssemblies:=False).Where(Function(t) t.ImplementsInterface(interfaceType)),
    9.                                 getName:=Function(i) GetNameFromCommandDefinition(i),
    10.                                 getLifetimeManager:=Function(i) WithLifetime.PerThread(i))
    11. End Sub

    Since there is a one-to-one mapping this works fine.
    Last edited by Merrion; Apr 13th, 2014 at 03:02 PM. Reason: Use generic parameter name...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width