I'm wondering what the general recommendation would be (attribute, interface, abstract class, or combination thereof) for the following implementation:
/// <summary>
/// Loads class specific information into a list for serialization. The class must extend PlugIn.
/// The filenames parameter is passed from a FileDialog.
/// </summary>
/// <param name="filenames">Accepts any number of filenames with fully qualified paths.</param>
public static void ExtractPlugInData(params string[] filenames)
{
List<Type> l;
foreach (string f in filenames)
{
Assembly a = Assembly.LoadFrom(f);
// lambda expression selects any class within a library extending the abstract PlugIn class
l = a.GetTypes().Where(type => typeof(PlugIn).IsAssignableFrom(type)).ToList<Type>();
if (l.Count > 0)
// write data to serializable class
WritePlugInData(f , l);
else
// throw exception
WriteLine("{0} :: No PlugIn Data Found" , a.FullName);
}
}
I realize there are advantages and disadvantages to each method. Obviously, attributes require some reflection (as do abstract extension and interface implementation). An abstract class takes our only base inheritance, and any future changes in an interface can break any existing plugins. So, as I see it, those are the disadvantages.
Performance is not an issue (unless there is something I don't see) since any reflection is only done once when a qualified class is extracted. The key pieces of data that are getting saved is a name for the plugin ("MyPlugIn"), the namespace ("SuperPlugIn.PlugInClass"), and the startup path for the .dll. Right now, with the abstract PlugIn class, the extension of the properties is enforced. This is more or less the same result if we implement an interface (IPlugIn).
We are allowing custom plugins to be written by end-users. With the plugins we are writing in-house, it is easy to teach and enforce a required structure for our application to instance a qualified class. However, I'm also considering the difficulties or inconvenience to the end-user should there be a major change.
All comments, suggestions, and questions welcome!!
Note: thanks go to Jon Skeet for the lambda expression in the snippet. :)
EDIT: I should have noted in the beginning that this is intended to be platform independent (i.e. Mono).
UPDATE: Based on the excellent recommendations, comments, and links below, a mix of attributes and interfaces is the best approach. Attributes let you load the assembly and check for required information and implementations rather safely without instancing the plugin classes/objects. This is ideal in situations where 3rd party or end users are allowed to create custom plugins. We can check to ensure that the proper contract implementation is in place where the attribute says it's suppose to be. We can check for required dependencies and resources and alert the developer of any problems before anything is instanced.
You want your end users to write plugins? I don't think that's a very good idea, unless your end users are programmers.
I'm going to keep my answer short this time since this is a pretty big honkin' dupe:
Plug-in architectures almost always involve classes in an external assembly implementing a specific interface in a common assembly;
There are already dozens of cookie-cutter .NET plugin implementations including Microsoft's own Managed Extensibility Framework. Don't reinvent the wheel.
Edit: For Mono, check out Mono.Addins.
I'd probably tend to use attributes. Extending the base class system with metadata is kind of exactly what they're for, and saying 'this class is a plugin' certainly fits that bill.
Assembly.GetTypes is a very expensive call, and I would avoid it where possible. (App startup time matters)
The faster way to do this is probably (I haven't benchmarked) an assembly-level attribute, which would be used like this:
[assembly: PluginClass(typeof(MyPlugin), more info)]
You can then call GetCustomAttributes on the Assembly, which would probably be much faster than GetTypes.
Using LINQ:
filenames.SelectMany(f =>
Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true)
.Cast<PluginClassAttribute>()
.Select(a => a.PluginType)
).ToList();
Related
I have a class MyClass which has a bug in the implementation. The class is part of a library, so I can't change the implementation of the class because it will silently change behavior for existing clients (clients who in this case may rely on the bug: See for example (https://connect.microsoft.com/VisualStudio/feedback/details/790160/httpclient-throws-operationcanceledexception-insead-of-timeoutexception))
I need to create a second version of the same class which includes the bug fix.
I've seen situations like this before but the naming I've seen was always incremental Eg MyClass2 , MyClass3.
These cases are probably quite rare, however I was wondering if there is a better way of naming these "versioned" classes.
I imagine a solution which grows in time and has multiple classes of these type which can get probably really confusing especially for a library. I imagine myself having to pick between MyClass, MyClassV2, MyClassV3 etc.
In an ideal world, new versions would introduce additional functionality while still remaining 100% backwards compatibility with previous versions of the API. Unfortunately, the ideal world remains elusive, and it is not always possible to retain full backwards compatibility. A versioned suffix is the appropriate pattern in this case.
The standard .NET naming convention is to use incremental numbering, like Class, Class2, Class3, etc.. This comes from the naming convention for COM interfaces, designed for exactly the use case you're describing. For example, the IHTMLDocument interface currently has 8 versions, from IHTMLDocument up through IHTMLDocument8.
The original Framework Design Guidelines book, by Cwalina and Abrams, explicitly recommended this practice, with the authors having this to say:
DO use a numeric suffix to indicate a new version of the existing API, if the existing name of the API is the only name that makes sense (i.e., it is an industry standard), and adding any meaningful suffix (or changing the name) is not an appropriate option.
// old API
[Obsolete("This type is obsolete. Please use the new version of the same class, X509Certificate2."]
public class X509Certificate { ... }
// new API
public class X509Certificate2 { ... }
The old convention, followed by the original Windows team, was to add the suffix Ex to new-and-improved versions of an API, which comes from the word "extend." This doesn't scale well, however, leading to functions confusingly suffixed ExEx. I don't think there was an ExExEx; everyone was afraid to touch those APIs. The Framework Design Guidelines recommend explicitly against this practice, the folks who went on to architect .NET having learned their lesson:
DO NOT use the "Ex" (or similar) suffix for an identifier to distinguish it from an earlier version of the same API.
[Obsolete("This type is obsolete. ..."]
public class Car { ... }
// new API
public class CarEx { ... } // the wrong way
public class CarNew { ... } // the wrong way
public class Car2 { ... } // the right way
public class Automobile { ... } // the right way
Obviously, as their last code sample hints, if you are adding support for a specific feature in the new version of the API, you would be best off naming the new class/interface with a reference to that particular feature.
And although the above has focused almost exclusively on classes and interfaces, the same logic would hold true for any member functions of that class that might be added in later revisions. The original function could retain its original name, with the newly added function having a different name that either reflects its iteration or its added functionality.
I was wondering if there is a better way of naming these "versioned" classes.
There is no .NET naming convention for "classes which fix bugs in other classes". I would advise with other developers in your workplace and see if they have any company conventions for such a thing. I think consistency is of importance more than the actual name.
And on a side note to your problem, I wouldn't create a new class at all. I would mark the method with DeprecatedAttribute and implement the logic inside the same class, exposing a new set of API methods which are properly documented to state they are here as a fix. The clients of your library are probably already familiar with MyClass, and doing so would ease the use for them, interleaving them the need to ask themselves each time "which version of this should I use".
I would copy all the behaviour of your existing class to a new one, rename the original one to indicate that the class is obsolete, rename the new one to the actual name from before and mark the original one (with the new name now) as [Obsolete] indicating that it should not be used any more. Thus all consuming code automatically invokles the new behaviour. So your new class with the correct behaviour gets the name of the original class, where the buggy one gets a version-number for instance.
For legacy code you can do the opposite, make a new class with new name and mark the old one as Obsolete. I know SDKs with a version-number, where the last number indicates the most recent version of the class, and all the others have such an attribute together with a notice within the docs mentioning that the class is superseded with a new version.
For clarity, if that happens, I use ClassV2. That indicates that it's another version of the class.
I think duplication class name will seriously confuse other people overtime. You extract method with c# interface and implement different version.
Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I just read in msdn/books that extension methods are useful to add methods to existing classes if the existing class source code is not available , however I have noticed in some very good written open source codes that extension methods are still used along with with inheritance (abstract, interface) on classes that have source code written by the author himself/herself.
This is just general question , no source code here.
A common reason is dependency management: Let's say you have a fairly general class User and a not-so-general class GravatarImage. Now it might make sense to be able to call SomeUser.GravatarImage() instead of GravatarImage.ImageForUser(SomeUser). This is not only convenience; in a large project, it might be hard for other programmers to find out the 'right' way to do something. IntelliSense will help a lot here.
However, the User class is a "backend" class and should not need to know anything about images, views, gravatars or URLs, so you want to keep dependencies clean.
A similar argument applies to LINQ, which basically consists of extension methods. These extension methods, extend the collection interfaces, so you can create a lot of functionality with very small interfaces. Implementing a new kind of IEnumerable is very easy, yet you gain all the functionality that is provided by LINQ.
The IEnumerable interface, to stick to the example, doesn't allow much more than getting an enumerator. Instead of asking each implementor to provide a Count method, you can call the extension method which will accomplish the same.
It is noteworthy, however, that a method like IEnumerable.Count() can be very slow (it has to touch every element), whereas a direct implementation of the underlying class could be as simple as returning a simple int.
A lot of the answers already here are great: I love using extensions for optional behavior, and on interfaces. There are a couple of other good reasons.
Avoiding abstract method overloads. Consider the following interface:
public interface IUserService
{
User GetUser(int userId);
User GetUser(int userId, bool includeProfilePic);
}
We can see how it might be useful to optionally include the profile pic when getting a user from a IUserService. But, with both methods on the interface, they could be implemented in totally different ways (something this simple probably wouldn't, but I run across this problem a lot). Using extension methods, overloads cannot have divergent behavior:
public interface IUserService
{
User GetUser(int userId, bool includeProfilePic);
}
public static class UserServiceExtensions
{
public static User GetUser(this IUserService userService, int userId)
{
return userService.GetUser(userId, false);
}
}
Respect encapsulation. If you have a bit of additional functionality that you want to put on a class, but it does not need any access to internal members of the class to function, and holds no state, then using an extension method is desirable. The fewer things that know about a classes internal members and state the less coupling you will have, and the easier it will be to maintain code in the long run.
A downside: you can't Moq Extension Methods
A lot of times this doesn't matter. It means that, in order to mock out behavior behind an extension method, you usually need to know how the extension method works, and mock the virtual methods it calls. This couples your tests to an implementation of the extension method. This is just annoying if your extension method is simple and unlikely to ever change. This is pretty bad if your extension method encapsulates some complex set of calls. For that reason, I usually only use extension methods for relatively simple behaviors.
In C#, providing extension methods for an interface is usually an attempt at approximating* mixins.
A mixin can also be viewed as an interface with implemented methods.
Although C# does not support mixins, providing extension methods to an interface class that others can implement is a nice way of "bolting on" functionality.
Here's a real-world example of a simple interface with bolted on functionality delivered as a mixin:
public interface IRandomNumberGenerator
{
Int32 NextInt();
}
public static class RandomNumberGeneratorExtensions
{
public static Double NextDouble(this IRandomNumberGenerator instance)
{
return (Double)Int32.MaxValue / (Double)instance.NextInt();
}
}
// Now any class which implements IRandomNumberGenerator will get the NextDouble() method for free...
* The big difference between C#'s approximation of mixins and the real thing is that in supported languages mixins can contain private state, where as extension methods on interfaces in C# can obviously only access public state.
A good way to think of extension methods is like a plugin-type architecture - they give you the ability to include/exclude functionality for a particular type instance. To answer your question specifically:
Why to use extension methods if source code is available instead of inheritance
The simplest answer to that would be for optional functionality. The most common, and probably the most important, reason for using extension methods is being able to extend a particular type without changing any core functionality. Deriving new types for the sake of adding a couple of methods is overkill, even if you had control over the source it would make more sense to make the type partial instead. Extension methods tend to be used to solve problems for particular scenarios and don't really merit going into the core code base. However, should you find yourself using them all over the place then that's a good indicator that your probably not using them correctly.
For example, consider the following extension:
var epochTime = DateTime.UtcNow.ToEpochTime();
ToEpochTime would return me the date time as Unix Time. This would be useful as an alternative way of generating a timestamp or serializing the date. However, it's quite a specific function so it wouldn't make sense being part of DateTime but by making it an extension method it allows me to simply include this type of functionality if & when required.
There are a couple of disadvantages I can think of with subclassing as an alternative to extension methods:
It can be excessive if you only want to add a couple of lightweight methods.
It can create problems if you already have a complex inheritance structure (especially if your class already has subclasses), or intend to have one in future.
I often use extension methods for bridging boundaries between namespaces in a way that increases readability and maintains separation of concerns. For example myObject.GetDatabaseEntity() reads quite nicely, but the code for GetDatabaseEntity() should be in the database section of the code, not in my business logic. By putting this code in an extension method I can keep everything where it belongs without adding the complexity of subclassing.
Additionally, if myObject was instantiated in my business logic before being passed to the database code, then the business logic would need to include the database namespace. I prefer to have each module's responsibilities clearly demarcated, and would prefer my business logic to know as little as possible about the database.
There are also a couple of tricks that extension methods are useful for (some of which have been mentioned already in other answers):
They can be applied to interfaces (LINQ uses this a lot).
They can be applied to enums.
They can be used as event handlers if you create them with the correct signature. (Not that I'd recommend doing this as it can lead to confusion, but it can save you from storing references to objects that you would otherwise need to stick in a collection somewhere - watch out for leaks!)
This may be a somewhat specialized case, but I've found extension methods useful when providing "rules" of various types to existing classes.
Say you have a classe SomeDataContainer, with lots of members and data, and you want to export certain pieces of that data in some cases, and other pieces in other cases.
You could do something like this in SomeDataContainer:
if(ShouldIncludeDataXyz()){
exportXyz();
}
(...)
private bool ShouldIncludeDataXyz(){
// rules here
}
private void ExportXyz(){ (...) }
... but I've found that this sometimes gets messy, especially if you have lots of classes, and many rules, etc.
What I've done in some cases, is to place the rules in separate classes, with one "rule class" for each "data class", and create the rules as extention classes.
This just gives me a hierarchy of rules in one place, separated from the core data - a separation I find useful anyway.
The resulting code would still be similar to the above:
// This now calls an extention method, which can be found
// in eg. "SomeDataContainerRules.cs", along with other similar
// "rules"-classes:
if(this.ShouldIncludeDataXyz()){
exportXyz();
}
This situation probably is not entirely uncommon to some of you: you have some functionality to put in a class but the perfect name (*) for that class is taken by one of the classes in the System namespace or other namespace/class that's not yours but you're using/importing.
(*) By perfect I mean small, concise and clear names.
For instance I have an Utils class that has a Diagnostics (mostly debug utils) class and a Drawing class. I could:
have a DrawingUtils class and a DiagnosticsUtils class, but that just smells like bad structure.
pick a thesaurus and be done with an worse, longer or awkward name that's casually still not taken.
Write class names in my native language instead of English.
Ask the smart guys at StackOverflow.
I think options 1-3 aren't promising :(
EDIT:
Since my chosen answer doesn't address the problem definitively (neither I do), what I'd recommend for people facing the same situation is to ask yourselves: Will you frequently use the conflicting BCL class/namespace? If no, then let your name conflict (as I did with Diagnostics). If yes, add a word that limits the possibilities of your class/namespace.
In practice, this means:
"Drawing": Something that draws.
"MyCustomControlDrawing": Something that draws only on MyCustomControl. e.g.: "WidgetDrawing".
EDIT2:
Another solution to take a look next time: Extension Methods (courtesy of Lawnmower).
I don't see any issue with keeping the names Drawing, Diagnostics etc. That's one of the purposes of namespaces, to resolve naming conflicts.
The beauty of namespaces is that they allow you to create classes with identical names. You can assign an alias to a namespace when you import it into your file with a using statement.
using MyAlias = My.Custom.Namespace;
this will keep your classes separate from Microsoft's.
you can then reference your classes as
MyAlias.Diagnostics
or you could alternatively assign an alias to Microsoft's namespace, but I wouldn't recommend this because it would confuse other developers.
To me, it really isn't worth the hassle of purposefully writing conflicting class names. You'll confuse other developers who aren't familiar with your codebase, because they will be expecting to use BCL classes but end up with yours instead (or vice versa). Then, you just waste their time when they have to write specific using aliases.
Honestly, coming up meaningful identifier names is a useful skill, but it isn't worth delaying your development. If you can't come up with something good quickly, settle for something mediocre and move on. There is little value in toiling over the names. I dare say there are more productive things you could be doing.
EDIT: I also don't believe that "small" is a component of a "perfect" identifier. Concise and clear, for sure, but if it takes a longer name to convey the purpose of a particular construct, so be it. We have intellisense, after all.
Use namespaces to disambiguate your classes from the classes in other namespaces. Either use fully qualified names or a using statement that tells the compile what you need:
using Type = MyReallyCoolCustomReflector.Type;
Now if you want to still use the Type class from the System namespace:
System.Type sysType = anObject.GetType();
Generally I try to avoid name duplicates but this doesn't always work out that way. I also like simple, readable and maintainable code. So as often it is a trade-off decision.
Well, if you want to avoid a namespace collision there are a couple of things you can do:
Don't collide, instead choose a unique name.
Example:
If you are creating a Math class you can name yours CamiloMartin.MathHelper
Use the long namespace to distinguish between collissions.
Example:
public class MyClass
{
public int SomeCalculation(int a, int b)
{
return MyNamespace.Math.SomeFunc(a, b);
}
}
Using an alias to differentiate.
Example:
using System.Math;
using SuperMath = MyNamespace.Math;
namespace MyNamespace
{
public class MyClass
{
public int SomeCalc(int a, int b)
{
int result = Math.abs(a);
result = SuperMath::SomeFunc(a, b);
return result;
}
}
}
Just for the record: .NET framework doesn't have neither Utils nor Diagnostics class. (But does have System.Diagnostics namespace.)
Personally I don't like general-purpose classes like Utils because their methods are not very discoverable (and usually either too general or too specific), therefore I would justify their use only as for internal classes.
As for the rest -- I agree with others on that namespaces are convenient. (Although I would thought twice to name the class if there is already a class in System with the same name, not because of name conflicts, but rather because the reason why I can't use 'original' class could mean that the class I'm about to create is semantically different.)
Often its possible to choose a more specific name. Take Utils for example. Absolutely everything can be called a utilitiy. For the reader of your code this classname is worthless.
Often utility classes are a collection of methods that didn't really fit anywhere else. Try to place them where they belong, or group them by some criteria, then use the group as a classname. Such grouping is in my experience always possible.
In general:
That's what we are doing (hey, we can refactor it later)
Used it once or twice but only on important classes. Especially useful if you don't know the 'perfect' name yet.
don't even think about this...
Using namespace aliases is no fun. So I avoid it if I can.
I'm working on a project in which I use Depency Injection. When registering a set of interfaces and classes, I need to point out the namespaces at which those interfaces and classes are located.
I don't like providing string constants though, mainly because it hurts refactorability. I don't like taking one of the interfaces/classes and get it's namespace either. For example:
typeof(FoodStore.Fruits.IApple).Namespace
because it looks odd having all these arbitrary type names lingering around (why choose IApple over IOrange?), only to distract from the actual point of the code. There's simply no sensible rule which type to pick.
I came up with the following solution.
Put a namespace anchor class in every namespace I need to reference:
namespace FoodStore.Fruits
{
/// <summary>
/// Serves as a type based reference to the namespace this class
/// is located in.
/// </summary>
public sealed class _NamespaceAnchor
{
}
}
Now I can use:
typeof(FoodStore.Fruits._NamespaceAnchor).Namespace
Whenever I refactor the namespace, I don't have to worry about the DI registrations.
Although this solution satisfies the question's requirements, I'm still not happy because now I have these sort of ugly empty classes hang around. I can't make them internal because - obviously - the references span across assemblies.
My question is: does anyone know of a more elegant solution?
No, there isn't anything better - namespaces aren't really first class concepts in the CLR, as far as I'm aware. Yes, Type allows you to ask it for a namespace - but namespaces are really for humans rather than the VM.
Note that unlike in Java, there's no access control at the namespace level. I haven't checked, but I suspect there's no particular metadata token for a namespace.
I can't think of anything about namespaces which would affect the CLR at execution time. Clearly they affect language compilers - but again, that's for the benefit of humans, so that we can organise types hierarchically and avoid specifying that hierarchy at every step.
I'd be concerned here that the namespace (which is really just part of the class name) has functional meaning in your application. If a later maintenance engineer moves some classes around, they may inadvertently break the injection system without realizing it. The error won't become apparent until runtime and could take a while to track down.
In this case, I would prefer a more explicit opt-in, such as using attributes. Here's one possibility:
public class TestInterfaceAttribute : Attribute { }
public interface IMyInjectableService { }
[TestInterface]
public class TestService : IMyInjectableService { }
public class RealService : IMyInjectableService { }
That said, most DI frameworks already either have some form of export meta-data (to help resolve the correct dependency for your particular use case) or are structured in a way that you define the dependency resolutions explicitly.