0

I have a class implementing an interface. Is there a way to tell if that class has been instantiated (via AppDomain maybe) and then get a reference to the object via the known interface?

I suppose this is related to dependency injection. Rather than having a library with registered objects, I'm looking for an alternative.

IAbstract
  • 19,551
  • 15
  • 98
  • 146
  • 2
    Why would you want to do it? It might be an XY problem – Fabjan Nov 18 '19 at 13:27
  • 1
    You're basically describing dependency injection (and perhaps the singleton pattern) so why can't you use a DI library? – DavidG Nov 18 '19 at 13:29
  • `Is there a way to tell if that class has been instantiated` what would the use case be for this? If you want to see if an object has ever been instantiated, you'd need to modify that object's class to provide some type of private static bool (or counter) that gets flagged when an object is [constructed](https://social.msdn.microsoft.com/Forums/vstudio/en-US/e16464c8-1b72-4485-9891-94da63c4ec2e/is-it-possible-to-tell-if-a-class-has-been-instantiated?forum=csharpgeneral) – Trevor Nov 18 '19 at 13:31
  • @DavidG: I'm not ready to commit to that. I.e. - I'm exploring options. So far, I've only one place that I would be implementing DI and including a DI library for one object will likely get me to rethink my approach. – IAbstract Nov 18 '19 at 13:32
  • 1
    I am voting to close this question as it needs clarification and [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Fabjan Nov 18 '19 at 13:37
  • 2
    Then I strongly recommend you change your approach, there's very little reason these days to not do DI. – DavidG Nov 18 '19 at 13:38
  • I agree with @DavidG, you could do a simple constructor injection to solve this easily without much change. – Trevor Nov 18 '19 at 13:39
  • Yep. I've voted to close with the duplicates that already tread the same ground. Thanks. – IAbstract Nov 18 '19 at 13:40

1 Answers1

1

You could set a static variable in the class that gets set when the constructor is called.

get a reference to the object via the known interface

This makes it sound like you only expect to have one instance of this class. If so, check out the Singleton pattern.

Smolakian
  • 414
  • 3
  • 15
  • Actually, I'm using a Singleton ... I'm rethinking how I'm doing this. – IAbstract Nov 18 '19 at 13:38
  • 1
    I downvoted this because it wasnt obvious what the OP is asking about and this answer looked more as a guess. Now it seems that it is one of the options that the OP has hence the upvote – Fabjan Nov 18 '19 at 13:41