1

I have 2 fields like

private IFruit fruit;
private Banana banana;

An instance of Banana is created like this:

var banana = new Banana(fruit);

I want to create an attribute for Banana fields to do the job of creating Banana instance for me!

3
  • 1
    Google for dependency injection. It does what you are looking for.
    – leppie
    Jul 12, 2011 at 9:17
  • 1
    not really clear what you want, sorry. Can you, please, redifine yuor question ?
    – Tigran
    Jul 12, 2011 at 9:18
  • You could also look into the Factory pattern. But still your question is not clear enough to give a good answer.
    – dowhilefor
    Jul 12, 2011 at 9:20

2 Answers 2

1

Attributes don't cause any code to be executed - you'll have to use reflection to access them. If you want you could implement a base class that has this behavior, and add the reflection code to the constructor:

abstract class AutoCreateBase
{
    public MyBase()
    {
        // Reflection to go through the fields, find the attributes, and use Activator.CreateInstance() on each
    }
}

class MyClass : AutoCreateBase
{
    [AutoCreate]
    private Banana banana;
}
0

Also some container like unity offer this functionality

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.