Unity - map a class to what it handles by interface?
Hi
I am using Unity and want to map my handler classes to the query definitions they handle e.g.:-
vb.net Code:
Public Shared Sub RegisterTypes(container As IUnityContainer)
Dim interfaceType As Type = Nothing
'Get the interface definition for the generic query handler interface we are looking for
interfaceType = GetType(IQueryHandler(Of ,))
container.RegisterTypes(AllClasses.FromAssembliesInBasePath(includeUnityAssemblies:=False, includeSystemAssemblies:=False).Where(Function(t) t.ImplementsInterface(interfaceType)),
getFromTypes:=Function() WithMappings.FromMatchingInterface(interfaceType),
getName:=Function(i) WithName.TypeName(i),
getLifetimeManager:=Function(i) WithLifetime.PerThread(i))
So - how do I register it so that when I pass in a class it can find the appropriate class that implements IQueryHandler of that class?
e.g. if I pass in:-
vb.net Code:
<DataContract>
Public Class GetServerDateTimeQueryDefinition
Inherits QueryDefinitionBase(Of DateTime)
How do I get it to return:-
vb.net Code:
Public Class GetServerDateTimeQueryHandler
Implements IQueryHandler(Of Query.Definitions.GetServerDateTimeQueryDefinition, DateTime)
Any ideas/links?
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:
Public Shared Function GetNameFromCommandDefinition(ByVal handler As Type) As String
'find out what tyoe the handler handles...
Dim handlerInterface As Type = handler.GetInterface("ICommandHandler`1", False)
If (handlerInterface IsNot Nothing) Then
' Get the name of the first generic class
If (handlerInterface.GetGenericArguments.Count > 0) Then
Return handlerInterface.GetGenericArguments(0).Name
End If
End If
Return handler.Name()
End Function
(This function goes in the initial container registration code e.g. )
vb.net Code:
Public Shared Sub RegisterTypes(container As IUnityContainer)
Dim interfaceType As Type = Nothing
'Get the interface definition for the generic interface we are looking for
interfaceType = GetType(ICommandHandler(Of ))
container.RegisterTypes(AllClasses.FromAssembliesInBasePath(includeUnityAssemblies:=False, includeSystemAssemblies:=False).Where(Function(t) t.ImplementsInterface(interfaceType)),
getName:=Function(i) GetNameFromCommandDefinition(i),
getLifetimeManager:=Function(i) WithLifetime.PerThread(i))
End Sub
Since there is a one-to-one mapping this works fine.