我正在尝试在统一容器中自动注册所有报告。
所有报告都实现了IReport,并且还有一个Report()属性,该属性定义了标题,描述和唯一键(因此我可以在不实例化具体类的情况下阅读这些内容)。
因此...
我得到像这样的报告类型
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
并按照以下方式注册:
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
对GetClassesWhichimplementInterface()
的调用返回了类型,并且Container.RegisterType()调用没有错误。如果我在注册调用后立即调用Container.Resolve(of Interfaces.IReport)
,则会出现以下异常:
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)
有谁能告诉我为什么容器没有保留注册?
答案 0 :(得分:1)
注册在容器中。问题是你在没有将命名注册作为参数传递的情况下调用resolve。
由于所有注册均使用以下代码执行:
Container.RegisterType(GetType(IReport), ReportType, ReportType.Name)
然后所有人都有一个名字。您必须提供名称以及能够从容器中解析依赖关系的类型。
您获得的错误是因为没有名称的注册类型映射。