System.Type 的自定义属性参数

发布于 2025-01-06 23:10:56 字数 738 浏览 0 评论 0原文

我想在我的统一容器中自动注册常见/简单服务。我认为最简洁的方法是通过自定义属性。

然后,我可以检查程序集中的所有(抽象)类并统一注册这些类型。

我缺少的信息是该类想要注册的接口

,例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蒲公英的约定 2025-01-13 23:10:56

这是可能的,你只需要写:

<AutoRegister(ForInterface := GetType(Stratego.Interfaces.IEngine))>

It is possible, you just have to write:

<AutoRegister(ForInterface := GetType(Stratego.Interfaces.IEngine))>
吻风 2025-01-13 23:10:56

我不完全理解你想要实现的目标,但我认为根据你的示例代码,你可以只放置一个空属性(类似于 )并使用它来查找您想要注册的所有课程。接口类型已经由注册的类实现,因此您可以在运行时从类型中提取它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文