System.Type 的自定义属性参数
我想在我的统一容器中自动注册常见/简单服务。我认为最简洁的方法是通过自定义属性。
然后,我可以检查程序集中的所有(抽象)类并统一注册这些类型。
我缺少的信息是该类想要注册的接口
,例如:
Public Class AutoRegisterAttribute
Public Property ForInterface As System.Type
Public Sub New(ForInterface As System.Type)
Me.ForInterface = ForInterface
End Sub
...
End Class
该类将按如下方式使用它
<AutoRegister(ForInterface:=Stratego.Interfaces.IEngine)>
Public Class StrategoEngine
Implements IEngine
Implements IDisposable
...
End Class
注意,我不只是想找到它实现的任何类,如 < code>IDisposable
我尝试使用泛型(泛型不能从 Attribute
继承)和类型参数(传入 IEngine.GetType 会导致“需要常量表达式”)来执行此操作”)
这可能吗?如果是这样,我怎样才能实现它?
I'd like to auto-register the common/simple services in my unity container. I think the cleanest way to do this would be via a custom atribute.
I can then examine all the (abstract) classes in an assembly and register those types with unity.
The piece of information I'm missing is the interface(s) that the class wants to be registered against
eg:
Public Class AutoRegisterAttribute
Public Property ForInterface As System.Type
Public Sub New(ForInterface As System.Type)
Me.ForInterface = ForInterface
End Sub
...
End Class
And the class would use it as follows
<AutoRegister(ForInterface:=Stratego.Interfaces.IEngine)>
Public Class StrategoEngine
Implements IEngine
Implements IDisposable
...
End Class
Note, I don't just want to find any class it implements as shown with IDisposable
I've tried doing this using generics (generics can't inherit from Attribute
), with a Type Parameter (Passing in IEngine.GetType results in a "Constant expression is required")
Is this possible? If so, how can I achieve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是可能的,你只需要写:
It is possible, you just have to write:
我不完全理解你想要实现的目标,但我认为根据你的示例代码,你可以只放置一个空属性(类似于
)并使用它来查找您想要注册的所有课程。接口类型已经由注册的类实现,因此您可以在运行时从类型中提取它。I don't fully understand what you're trying to achieve, but I think according to your sample code that you could just put an empty attribute (something like
<AutoRegister>
) and use it to find all classes you want to register. The interface type is already implemented by the registered class, so you can just extract it from the type at runtime.