Basic
Basic

Reputation: 26756

Custom Attribute parameter of System.Type

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?

Upvotes: 1

Views: 333

Answers (2)

Jb Evain
Jb Evain

Reputation: 17499

It is possible, you just have to write:

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

Upvotes: 3

Itai Bar-Haim
Itai Bar-Haim

Reputation: 1674

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.

Upvotes: 0

Related Questions