C#: Can someone explain the practicalities of reflection? [duplicate] - c#

This question already has answers here:
When do you use reflection? Patterns/anti-patterns
(17 answers)
Closed 9 years ago.
So I tried searching SO hoping someone had a good explanation of this, with no luck.
I asked another friend of mine a different question (which I've now forgotten) and his answer was simply "reflection" before he signed off.
I am still very new to the C# world, having been an amateur VB.net programmer (also JavaScript, ActionScript, and C), and am trying as hard as I can to grasp these advanced concepts.
There's lots of philosophical answers -- "application looking at itself" -- but they don't provide any practical hints on what is actually going on or how it is used within that context.
So, what is reflection, why is it important, and why/how do I use it?

Reflection provides the ability to determine things and execute code at runtime.
You don't have to use it if you don't want to, but it is extremely handy for dynamic behavior.
For example:
a) You can use reflection to configure your application by loading an external configuration file and starting services based on it. Your application wont have to know in advance about the classes that implement those services, as long as they conform to a specific interface or API.
b) Using reflection you can generate classes and code on the fly, which simplifies certain programming tasks since the programmer does not have to explicitly create all the needed code.
c) Reflection is also invaluable for programs that work by examining code. An example of that would be an IDE or a UI designer.
d) Reflection helps you reduce boilerplate code.
e) Reflection is handy for defining mini Domain Specific Languages (DSL) in your code.

(my defintion)
Reflection is the ability to write static code that executes code at run-time, that is normally determined at compile time.
For instance, I could call a class method to draw by compiling in that command eg:
pen.DrawLine()
or With reflection, I can first see if my object has a method called "drawline" and if so, call it. (Note this isn't the actual C# Reflection syntax)
if(pen.Methods.Contains("DrawLine"))
{
pen.InvokeMethod("DrawLine"))
}
I'm no reflection master, but I used reflection for a plug-in architecture.
With reflection I can load a .NET assembly (a dll in this case) at run time, find out all the types that are in the .NET Assembly, see if any of those types implement a specific interface, and if so, instantiate the class, to which I invoke the interface methods.
I know that use-case is a bit technical, but essentially reflection allows me to load plug-ins dynamically (ie at run-time), and lets me make type-safe calls to it.

The most common use of reflection is an extension of what used to be called RTTI (run-time type information) and was primarily the domain of C++ programmers.
Reflection is a side-effect of the way .net is built and that Microsoft elected to expose the libraries they used to create Visual Studio and the .net run-time to developers outside of Microsoft.
Most of the reflection library focuses on type discovery and creation that can be invoked at run-time. This allows for some very powerful self-referential code. Take the following example at the heart of our configuration management system (some bits deleted for clarity):
public static IMyCompanySetting UnwrapSetting(XmlNode settingNode)
{
string typeName = settingNode.Attributes["type"].Value;
string typeAssembly;
if(settingNode.Attributes["assembly"] != null)
{
typeAssembly = settingNode.Attributes["assembly"].Value;
}
Type settingType = null;
Assembly settingAssembly = null;
try
{
// Create an object based on the type and assembly properties stored in the XML
try
{
settingAssembly = Assembly.Load(typeAssembly);
if (settingAssembly == null)
{
return null;
}
}
catch (Exception outerEx)
{
try
{
settingType = GetOrphanType(typeName);
}
catch (Exception innerEx)
{
throw new Exception("Failed to create object " + typeName + " :: " + innerEx.ToString(), outerEx);
}
}
// We will try in order:
// 1. Get the type from the named assembly.
// 2. Get the type using its fully-qualified name.
// 3. Do a deep search for the most basic name of the class.
if (settingType == null && settingAssembly != null) settingType = settingAssembly.GetType(typeName);
if (settingType == null) settingType = Type.GetType(typeName);
if (settingType == null) settingType = GetOrphanType(typeName);
if (settingType == null) throw new System.Exception(
String.Format("Unable to load definition for type {0} using loosest possible binding.", typeName));
}
catch (Exception ex)
{
throw new CometConfigurationException(
String.Format("Could not create object of type {0} from assembly {1}", typeName, typeAssembly), ex);
}
bool settingIsCreated = false;
IMyCompanySetting theSetting = null;
// If the class has a constructor that accepts a single parameter that is an XML node,
// call that constructor.
foreach (ConstructorInfo ctor in settingType.GetConstructors())
{
ParameterInfo[] parameters = ctor.GetParameters();
if (parameters.Length == 1)
{
if (parameters[0].ParameterType == typeof(XmlNode))
{
object[] theParams = { settingNode };
try
{
theSetting = (IMyCompanySetting)ctor.Invoke(theParams);
settingIsCreated = true;
}
catch (System.Exception ex)
{
// If there is a pre-existing constructor that accepts an XML node
// with a different schema from the one provided here, it will fail
// and we'll go to the default constructor.
UtilitiesAndConstants.ReportExceptionToCommonLog(ex);
settingIsCreated = false;
}
}
}
}
This code allows us to create a limitless number of classes that implement IMyCompanySetting and serialize and deserialize themselves using XML. Then, given a chunk of XML that is the output of object serialization, the system can turn it back into an object, even if the object itself is from a library that the serialization library doesn't have staticly linked.
There are 3 things that reflect does here that would be impossible without it:
Load an assembly at run-time based on its name.
Load an object from an assembly at run-time, based on its name.
Call an object constructor based on signature for an object of a class that is not known at compile time.

Say you have two alternate implementations of an interface. You want to allow the user to pick one or the other, via a simple text config file.
With reflection, you can simply read the name of the class whose implementation you want to use from the config file (as a string), and instantiate an instance of that class.

Reflection lets you dig into an assembly and use it, no matter that you don't have it referenced later.
Consider a plug-ins system, in which the host doesn't know about the plug-ins it will hold; with Reflection (and the correct architecture), you can construct a simple solution achieving this.
Consider another scenario in which you must to call the method on an object given a string, Reflection gives you the approach to achieve this as well.
There are many other usages but i hope these two, open your apetite to this excellent feature of CLR

It's sometimes useful to be able to read properties or invoke methods of a class without knowing what properties or methods a class has at design time. The way to accomplish this is with reflection. As demonstrated by the code below, you can get a list of all properties on a class and retrieve their values without knowing anything about it at compile time. Or you can get a method by name, even if you don't know the name of the method at compile time, and invoke it via reflection. This would allow you, for example, to create a scripting language that operates on objects defined in another user-supplied DLL. (Of course you can also enumerate all methods in a class or retrieve a specific property by name, but these cases are not demonstrated in the code below.)
class Program
{
static void Main(string[] args)
{
UserDefinedClass udc = new UserDefinedClass();
udc.UserProperty = "This is the property value";
ClassTracer ct = new ClassTracer(udc);
ct.TraceProperties();
ct.CallMethod("UserFunction", "parameter 1 value");
}
}
class ClassTracer
{
object target;
public ClassTracer(object target)
{
this.target = target;
}
public void TraceProperties()
{
// Get a list of all properties implemented by the class
System.Reflection.PropertyInfo[] pis = target.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in pis)
{
Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(target, null));
}
}
public void CallMethod(string MethodName, string arg1)
{
System.Reflection.MethodInfo mi = target.GetType().GetMethod(MethodName);
if (mi != null)
{
mi.Invoke(target, new object[] { arg1 });
}
}
}
class UserDefinedClass
{
private string userPropertyValue;
public string UserProperty
{
get
{
return userPropertyValue;
}
set
{
userPropertyValue = value;
}
}
public void UserFunction(string parameter)
{
Console.WriteLine("{0} - {1}", userPropertyValue, parameter);
}
}

Reflection is using the code to examine the code itself. For example, instead of calling foo.DoBar() you could call:
foo.GetType().GetMethod("DoBar").Invoke(foo,null);
That seems like a round-about method of getting to the same destination, but it can also be used to do some black magic that might break the rules, like calling private methods on framework classes, for example. It can also be used to actually generate code and output new binaries, and a whole slew of things that are extremely useful to a small group of people.
For more information, check out the MSDN section on Reflection.

There are many cases in which the application should not assume much about itself and should look at runtime to see what it actually is. This is where reflection comes into the show. For example, ASP.NET makes no assumption about the membership provider you use except that it inherits the appropriate class. It uses reflection to lookup the class at runtime and instantiate it. This gives out a great deal of extensibility due to decoupling and decreasing dependencies between classes.
This is, of course, only a single use case for reflection. There could be many other cases where it might be very useful.

Andrew Troelsen, author of Pro C# 2008 and the .NET 3.5 Platform, defines reflection this way:
In the .NET universe, reflection is the process of runtime type discovery.
I'm not sure I could give you an accurate explanation of what that means, but I can tell you how I've used it.
I can put a user-defined attribute on an assembly (dll). Using reflection at run-time, I can inspect all of the assemblies in a certain directory location to see if they have this attribute defined. This can clue my application on how to use the assembly, say as a plug-in.
I've also used reflection to load and save application settings.
For what it's worth, unless you're using reflection, I'm not sure what it has to do with your GUI throwing exceptions.
About the only thing I know about C#
reflection is that it is annoying as
hell because all my GUI apps like to
throw incredibly annoying, pointless
"Exception has been thrown by the
target of an invocation" exceptions at
Application.Run(new frmMain());,
instead of stopping where the real
problem happened (as shown in the
innerException).
Your statement makes me believe you have few if any try/catch blocks anywhere in your application such that every exception is percolating back to the top of the call stack. If you are using Visual Studio 2005/2008 in debug mode, go into the Debug menu and select the Exceptions... menu option. Inside the Exceptions dialog, check the checkboxes under the Thrown column. Now, when you run your application and an exception is thrown, the debugger will break where the exception is thrown.

Let's say you have some business entities which all come derive from a base class called Entity. Let's also say that you need/want all the derived classes to be cloneable. You can implement a method "Clone" (interface ICloneable) on the base class which would loop through all the properties of the current class (although it is implemented at the Entity class) and copy them to the cloned object. This is a case where Reflection can really help. Because you can't know the name and the count of the properties at the base class. And you don't want to implement the method in all derived classes. However you might want to make the method virtual.

Other people have answered for
what is reflection, why is it important
So I will be answering following questions only.
How do I use it?
Through following namespaces
System.Reflection
System.Reflection.Emit
Why do I use it?
To invoke/inspect assembly types, members, properties
When you look at a product like Reflector, being able to inspect code structure is more than practical enough.

If you run fast and furious, maybe you're inheriting from an object and need access to a private field. You don't have source, but thats ok you have Reflection. (hacky I know)
A more legitimate use I've seen is to use reflection in implementing C# generics where I want to do some operation on the generic type that isn't otherwise available. The only operations available on a generic type are those made available with a generic constraint (ie, if you constrain the generic type to implement IFoo, you can use IFoo methods on instances of that class). Some operations though just aren't available- for instance I was taking a generic class that was supposed to have a particular non-default constructor. I couldn't constrain the generic method to only accept generic type parameters with that constructor, but at least I could try and use that constructor when implementing the generic via reflection.
I use reflection sparingly but it occasionally comes in real handy.

I have used reflection to implement a custom data bindings system.
For example, with my bindings API I can write the following:
Binding b = new Binding(textBox, "Text", myObject, "Text", BindingMode.Bidirectional);
Any changes to the text in the textBox object are detected by the Binding object (which attaches to the TextChanged event) and passed into the myObject.Text property. Changes to myObject.Text are detected (by its TextChanged event) and passed into the textBox.Text member.
I implemented this system using reflection. The Binding constructor is declared as:
Binding(object, string, object, string, BindingMode)
The system therefore works with any object (with one important proviso).
I inspect the first object and find the member corresponding to the named member in the first string (textBox and "Text", ie. does textBox have a member called "Text"). Repeat with the second object and string.
Proviso: for objects to be used in this scheme they must implement the informal requirement that any bindable property must have a corresponding PropertyNameChanged event. Happily, pretty much all the .Net UI components follow this convention.
I then inspect the object for the requisite PropertyNameChanged events, add event handlers to them, and everything is set.
NB. I implemented this in .Net 1.0, so it predates Microsoft's bindings implementation - which I have not yet got round to investigating.

Practical Application
Use reflection for aligning Data with objects, as in a data mapping situation. For example, you can map a database column to an object's property. If you were to write an Object Relational Mapper, you would need some way to get from a configuration setting (i.e. DatabaseColumnName maps to Class.MemberName) to the objects to which it referring.

Reflection is so named because it allows ones code to take a look at itself just like looking in a mirror.
As previously mentioned reflection may be used to create new instances using a class name. Serialization is also powered by reflection. In this case the code examines all the serializable fields and serializes those recursively until the entire graph has been consumed and its byte form written.
Reflection allows one to escape static typing at compile time by discovering types, methods, fields etc at runtime. Many dynamic languages on the JVM (not sure about CLR but id imagine the same is true) use reflection to dispatch methods.

In terms of a practical use for reflection we have used it to allow our customers to provide their own localisation.
With our applications we provide a local resource database that the client can work through providing language translation for all strings, menu items, dialog controls...etc. With this client translated database in place we then use reflection on application launch and iterate through all our controls and replace default language strings with the client supplied translated strings.

There are many uses for reflection that have already been detailed here but another use might be to log the state of an object including its private members for use in debugging.

Can you post some sample code which shows how you are performing reflection? Do you have the PDB files in the same location as the assembly on which you are using the reflection API's?
If so, then in Visual studio go to the Debug menu -->Exceptions and check the check box "Common Language runtime thrown". Run your application in debug mode. Hopefully the debugger should break at the point in your reflected assembly at which the real exception is being thrown.

Related

Roslyn 2.x CodeFix that implements a missing interface, delegated to a member, VS 2017

BACKGROUND
I am seeking to create a Roslyn CodeFix that will respond to a Diagnostic warning from the built in Analyzer shipped with Visual Studio, that will identify the interface that is not - or is partially - implemented, allowing me to loop through the missing members, and generate custom code that delegates a method call to a Member field of a type that implements the interface.
(The Roslyn Analysers and CodeFixes that ship with Visual Studio do offer this functionality, but I need to customise and extend the generation of code, which is not possible as the Microsoft implementations are all marked as internal.)
Please note: The interface is almost always going to be located in an external, third-party assembly, to which I do not have access to the source.
e.g. starting from:
public class CustomDocumentDBClient : IDocumentClient
{
}
The desired outcome would be similar to the following (in practice I will be creating multiple versions that add additional code to wrap the method calls, once the basic principals are working):
public class CustomDocumentDBClient : IDocumentClient
{
// Field to which calls are delegated, initialised by the constructor
private readonly IDocumentClient _documentClientImplementation;
// Constructor
public CustomDocumentDBClient (IDocumentClient documentClientImplementation)
{
_documentClientImplementation = documentClientImplementation;
}
// Interface method that delegates to private field for invocation
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string documentLink, object attachment, RequestOptions options = null)
{
return _documentClientImplementation.CreateAttachmentAsync(documentLink, attachment, options);
}
// Interface method that delegates to private field for invocation
public Task<ResourceResponse<Attachment>> CreateAttachmentAsync(string documentLink, Stream mediaStream, MediaOptions options = null, RequestOptions requestOptions = null)
{
return _documentClientImplementation.CreateAttachmentAsync(documentLink, mediaStream, options, requestOptions);
}
...
other methods
...
}
WHAT I HAVE TRIED
I have spent some time reading tutorials regarding the Syntax Tree and Semantic Model functionality of Roslyn.
I have also examined the Roslyn source code from GitHub - which does include the exact feature that I wish to implement; however, the code is heavily interwoven throughout various complex classes, and is implemented as internal methods, which cannot be overridden or extended, or indeed extracted into a standalone project.
From investigating multiple samples, and also a related SO question How to see if a class has implemented the interface with Roslyn I have concluded that I must use the Roslyn Semantic Model to obtain information about the interface, and it's declared members.
Once I can obtain the interface Members, I am able to build the required output code using the SyntaxFactory, and I have used the 'Roslyn Quoter' for guidance.
Creating a CodeFix from the default template, that responds to the correct Diagnostic codes is straightforward, and this is functioning.
ISSUES
The problem I am having, is taking the token identified by the Diagnostics Location, which appears to be a SimpleBaseTypeSyntax token, and
Verifying that it is actually representing an interface,
Obtaining a Symbol definition that allows me to enumerate the Members of the third-party interface.
The Syntax Visualizer indicates that the interface declaration node is of type SimpleBaseType.
I am therefore using the following code to obtain the token from the Syntax Tree as SimpleBaseTypeSyntax-
// Find the interface Syntax Token detected by the diagnostic.
var interfaceBaseTypeSyntax =
root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf()
.OfType<SimpleBaseTypeSyntax>().First();
a) This does return a token that contains the information of the relevant node in the Syntax Tree - however, I cannot see any 'InterfaceTypeSyntax' type or IsInterface method to validate that it is actually an interface.
b) I believe I should be able to use semanticModel.GetSymbolInfo(interfaceBaseTypeSyntax), however this always returns null - bear in mind the interface is declared in an external assembly.
Is there something I need to do to make that information available through GetSymbolInfo, or is there another approach I should be taking...?
Many thanks for your advice...
It's rather embarrassing to have found this so quickly after posting, but the solution seems to be to refer to the Identifier which is a descendant of the SimpleBaseTypeSyntax.
var interfaceSymbolInfo =
semanticModel.GetSymbolInfo(interfaceBaseTypeSyntax.DescendantNodes().First());
And, by calling:
var interfaceTypeInfo =
semanticModel.GetTypeInfo(interfaceBaseTypeSyntax.DescendantNodes().First());
I can then use interfaceTypeInfo.Type.IsInterface to verify I have indeed found an interface type, and also access interfaceTypeInfo.Type.GetMembers().
The answer was staring me in the face via the Syntax Visualizer.
I'm leaving this open for now, in case others have a better solution... thanks!
In this case, the syntax node you are looking at refers to a type not a symbol. GetSymbolInfo will return null if the node you pass in is not a symbol. You want to use semanticModel.GetTypeInfo(interfaceBaseTypeSyntax).

What is Reflection property of a programming language?

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.

Member verification vs Interface

I was ready up on Ruby's method of enforcing interfaces w/ dynamic typing by checking for the existence of methods/properties that satisfy an interface.
In what ways is this overall just a better design principle than using interfaces? What are the pros/cons. For example you could implement the same concept in C# but I'm not sure if it would have the same value,
public class Foo
{
public Foo(dynamic _obj)
{
MethodInfo[] methods= _obj.GetType().GetMethods();
if (!methods.Any(x => x.Name == "SomeRequiredMethod")
{
throw new ArgumentException("Object does not meet interface requirements.");
}
}
// proceed with functionality that requires the method
}
And of course you could extend this to check more than just the name, like the signature, return type, etc.
Thoughts?
I can see several major issues problems with this approach:
reflection is slow
dynamic calls are also much slower than strongly-typed calls
the code is more complicated
And I can't see any advantage, except perhaps for very specific needs...
C# was designed as a static, strongly-typed language, and even though it now has some dynamic capabilities, they should only be used when there is no strongly-typed alternative.
If you really need to use the object dynamically, don't check the members manually: instead, put the code in a try block, and catch the RuntimeBinderException that will occur if a member you call is missing.

What is the best way to resolve an object?

I've written a resolver so I can have a very primitive DI framework. In the framework I allow for a dependency resolver to specify what default types to load if nothing is specified or registered.
However, the way I do the default loading has got me wondering. I'm not sure I'm doing it the best way it could be done.
Example:
T LoadDefaultForType<T>()
{
T _result = default(T);
if (typeof(T) == typeof(ISomeThing)
{
result = new SomeThing();
}
... more of the same
else
{
throw new NotSupportException("Give me something I can work with!");
}
return _result;
}
Update
The use of this would be to get the default object for a given interface in the event that a module or assembly has not configured the interface with a concrete type.
So for instance:
IoC.Resolve<ISomeThing>();
would need to return back to me a SomeThing object if nothing else has been registered to ISomeThing. The LoadDefaultForType in this case is kind of a last ditch effort to use a default (in this case whatever my domain model is).
The Resolve might shed some light on this as well:
T Resolve<T>()
{
T _result = default(T);
if (ContainedObjects.ContainsKey(typeof(T))
_result = (T)ContainedObjects[typeof(T)];
else
_result = LoadDefaultForType<T>();
return _result;
}
Any thoughts? Is there a better way to load default types given that I'm trying to allow for a Convention Over Configuration approach?
A few of suggestions:
You could create an attribute that can be used to mark the default implementation type of a particular interface. When you attempt to resolve the type, you could search for this attribute on T and use reflection to dynamically instantiate the type.
Alternatively, you could use reflection to search the available (loaded) assemblies or a concrete type that implements the interface. This can be a slow and expensive processes, so it would only make sense if the default case is rare.
Finally, if you're comfortable with naming conventions, you could search for a class that has the same name as the interface but without the leading "I". Not the best approach, but certainly one that can be made to work in a pinch.
public T LoadDefaultForType<T>()
where T : new()
{
T _result = new T();
return _result;
}
the code above would be a better way, but im not sure what it is your're trying todo, more information would help give u a better way of doing whatever it is you're trying to achieve.
I suggest taking a look at Unity for dynamically loading types, ie. Dependency injection
Neil's approach is the best if T can be resolved (I think it also has to be in the same assembly?).
Within your class, you could create an internal "registry" of sorts that could be used with System.Reflection to instantiate items without the giant switch statement. This preserves your "convention over configuration" while also keeping you DRY.
Edit
Combined with one aspect of LBushkin's answer to show some working code. (At least, it compiles in my head, and is taken from an example that I know works...)
public T LoadDefaultForType<T>()
{
try
{
string interfaceName = typeof(T).AssemblyQualifiedName;
// Assumes that class has same name as interface, without leading I, and
// is in ..."Classes" namespace instead of ..."Interfaces"
string className = interfaceName.Replace("Interfaces.I", "Classes.");
Type t = Type.GetType(className, true, true);
System.Reflection.ConstructorInfo info = t.GetConstructor(Type.EmptyTypes);
return (T)(info.Invoke(null));
}
catch
{
throw new NotSupportException("Give me something I can work with!");
}
}
Note that - as written - it won't work across assembly boundaries. It can be done using essentially the same code, however - you just need to supply the assembly-qualified name to the Type.GetType() method. (fixed - use AssemblyQualifiedName instead of FullName; assumes that interface and implementing class are in same assembly.)
One way would be to have a list of AssemblyQualifiedName pairs, with the first containing the base type and the second containing the child to be insantiated. It could be in your App.config or an XML file or whatever else is convenient. Read this list during start-up and use it to populate a Dictionary to use as a look-up table. For the key, you could use the AssemblyQualifiedName of the base, or perhaps the corresponding Type instance. For the value, you should probably consider getting the ConstructorInfo for the child type.
A better way to load the default types is to provide an add method that stores the type in a hash table. This decouples the dependency container from the registration logic.
You may choose later to change the registration code to read the types from some file or something.

Enforce Attribute Decoration of Classes/Methods

Following on from my recent question on Large, Complex Objects as a Web Service Result. I have been thinking about how I can ensure all future child classes are serializable to XML.
Now, obviously I could implement the IXmlSerializable interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a string so I may just write my own.
However, to serialize to XML, I am simply decorating the class and its members with the Xml??? attributes ( XmlRoot , XmlElement etc.) and then passing it to the XmlSerializer and a StringWriter to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.
The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.
Is there any way to enforce attribute decoration? Can this be done with FxCop? (I have not used FxCop yet)
UPDATE:
Sorry for the delay in getting this close off guys, lots to do!
Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. Fredrik Kalseth's answer was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!
+1 to the other guys for similar suggestions :)
I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.
UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this:
[TestClass]
public class When_type_inherits_MyObject
{
private readonly List<Type> _types = new List<Type>();
public When_type_inherits_MyObject()
{
// lets find all types that inherit from MyObject, directly or indirectly
foreach(Type type in typeof(MyObject).Assembly.GetTypes())
{
if(type.IsClass && typeof(MyObject).IsAssignableFrom(type))
{
_types.Add(type);
}
}
}
[TestMethod]
public void Properties_have_XmlElement_attribute
{
foreach(Type type in _types)
{
foreach(PropertyInfo property in type.GetProperties())
{
object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);
Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName);
}
}
}
}
You can write unit tests to check for this kind of thing - it basically uses reflection.
Given the fact this is possible I guess it would also be possible to write a FxCop rule, but I've never done such a thing.
You can write an FxCop rule or even check for the attributes by calling GetType() in the base class's constructor and reflecting over the returned type.
A good FXCop rule (and one which I am finding I need right now) would be to check that all objects that are being added to the ASP.NET Session have the Serializable attribute. I'm trying to move from InProc session state to SQL Server. First time I requested a page, my site blew up on me because non-serializable objects were being stored in Session. Then came the task of hunting through all the source code looking for every instance where an object is set in the Session... FXCop would be a nice solution. Something to work on...
You can also use this concept/post-processor to enforce relationships between attributes and use similar login to enforce relationships between classes and attributes at compile time:
http://www.st.informatik.tu-darmstadt.de/database/publications/data/cepa-mezini-gpce04.pdf?id=92

Categories