views:

23

answers:

1

Hi All,

I'm trying to automatically register all reports in a unity container.

All reports implement IReport and also have a Report() attribute which defines the title, description and unique key (so I can read these without instantiating a concrete class).

So...

I get the report types like this

Public Shared Function GetClassesWhichimplementInterface(Of T)() As IEnumerable(Of Type)
    Dim InterfaceType = GetType(T)
    Dim Types As IEnumerable(Of Type)

    Types = Reflection.Assembly.GetCallingAssembly.GetTypes()

    Return Types.Where(Function(x) InterfaceType.IsAssignableFrom(x))
End Function

And register them like this:

Public Sub RegisterReports()
    Dim ReportTypes = ReflectionHelper.GetClassesWhichimplementInterface(Of IReport)()
    For Each ReportType In ReportTypes
        ''Previously I was reading the report attribute here and using the defined unique key. I've stopped using this code to remove possible problems while debugging.
        Container.RegisterType(GetType(IReport), ReportType, ReportType.Name)
    Next
End Sub

There are types being returned by the call to GetClassesWhichimplementInterface() and the Container.RegisterType() call is made without errors. If I call Container.Resolve(of Interfaces.IReport) immediately after the register call, I get the following exception:

Resolution of the dependency failed, type = "MyProject.Interfaces.IReport", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, MyProject.Interfaces.IReport, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:

  Resolving MyProject.Interfaces.IReport,(none)

Can anyone tell me why the container isn't preserving the registration?

+1  A: 

Hi,

The registration is in the container. The thing is that you are calling resolve without passing a named registration as a parameter.

As all your registrations were performed using the following code:

Container.RegisterType(GetType(IReport), ReportType, ReportType.Name)

Then all of them have a name. You must provide the name along with the type to be able to resolve the dependency from the container.

The error you are getting is because there is no type mapping registered without a name.

Damian Schenkelman
Thanks for spotting the silly mistake
Basiclife