I have an object (x) with about 100 properties. Most of these properties are reference types that will need to be instantiated before I can do anything with x. Also, many of the properties on x will have properties that will also need to be instantiated.
I've thought to use reflection and recursion, but I'm still a little bit stuck on how the implementation would work. My current implementation involves looping through the PropertyInfo Array, and using SetValue from Activator.CreateInstance. As I drill down through x, I'm getting a lot of exceptions:
No parameterless constructor defined for this object.
Cannot create an abstract class.
Property set method not found.
Should I just account for these cases, or is there a better way to be doing this? Ultimately, it's not assigning values to everything I need still. Thanks for your help.
Probably this is overkill, but having such a big object which appears to refer to a hierarchy of classes (you mentioned abstract classes), I'd use a properly configured DI container such as Unity, to do the work for me.
You are looking for Dependency Injection, .NET included Managed Extensibility Framework, which supports creating objects with properties and with proper lifecycle control.
However, it will still give exceptions when it cannot instantiate types, but instead of creating all types, MEF provides attributes and other ways to control what types should be instantiated.
Related
I'd like to use C#'s reflection and custom attributes to simplify registering a series of types with a central management class (i.e. it provides static methods taking a string key and invoking/retrieving the proper method/parameter for the associated type). Looking at other questions here and a couple places elsewhere, it seems like the best way of doing so is to simply iterate through all public types of the assembly -- since it's intended to be a library -- and check if each type has the proper attribute before adding the relevant values to the underlying Dictionaries. The reflection and iteration will definitely be slow, but I can live with it since it should only occur once.
Unfortunately, I can't figure out how to get an attribute from a type. For methods and assemblies, I can use CustomAttributeExtensions.GetCustomAttribute<MyAttribute>(base) from System.Reflection.Extensions, but that doesn't provide an overload for Type; the same for Assembly.GetCustomAttribute(Assembly, Type) and the .IsDefined(...) methods used in this question. Other suggestions use methods on the Type itself that, from the documentation, seem to be loaded from mscorelib.dll, but it didn't seem to be showing up in Intellisense even after adding the reference and I'm not sure how that .dll interacts with .NET Standard, anyway (as in, does it reduce the ability to run on arbitrary platforms at all?)
Am I missing something obvious, or is it really this hard to get an Attribute back off of a Type?
Try typeof(YourType).GetTypeInfo().GetCustomAttributes();
Is there a method to understand if a generic C# Object is part of a collection? And is there a way to retrieve said collection?
I know an Object is not aware of being part of another (no references stored anywhere about parents) but maybe one could use reflection on generic collections.
To answer original question : no, you're not supposed to be able to find parent collection of an object, and reflection probably won't help.
But you may be able to achieve what you need by modifying behavior of ICollection.Add() by using extension methods and storing in each added objects a reference to their common container.
Putting additional data in objects seems to be achievable, as it is stated here :
How can additional data be associated with existing objects using extension methods?
There may be other solutions to achieve what you need, but on my self I'd go with something like that.
I am having a situation that I have a common reference object that is being pass around as parameter to different operation object. It makes the code very messy to pass it around.
Is there anyway to make it like a reference to every operation (like a session)? However, it is just a core code library. Using static class is not the solution.
Thanks
Solution 1 - You can use singletons. They guarantee that there is only one instance of the class in the running code.
Solution 2 - why don't you put the shared reference object as a property of the object with those operations? That way, each operation has access to it. You can do some fancy stuff like if the reference property is null, throw an exception or so.
There are two general approaches to this that I know of:
a) Use IoC and a constructor dependency to pass in your shared object. As you mentioned if this object is used in many, many places this pollutes the interface and in many cases adds a lot of clutter.
b) Use an ambient context: Create a interface based singleton that may be accessed by the classes that need the object instance. Have a setter within the singleton that allows you to override the instance (e.g. for unit testing) so testing the code is still possible.
Maybe the Ambient Context Pattern could work for you? http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/
When we should use constructor over properties or vice versa while assigning values.
A constructor is a very convenient and powerful type of contract - a way to require consumers to provide certain information before they can even use your object. So for information that is necessary for the instance to function properly, use constructor parameters. This is the underlying concept of dependency injection - anything you depend on to do your job, must be injected (provided) to you before you begin.
Properties can represent an interesting problem. In general, experience has taught me that wherever possible, properties should be read-only and objects should generally be as externally immutable as possible. Adding a public setter to a property is a multiplier of complexity for your class. There are of course always types of objects - entities are a good example - where setters make sense. But for most objects, the pattern of "write-to via constructor" / "read-from via properties" for state has vastly reduced complexity and bug risks in the applications I've been responsible for.
Use constructor if the parameter values are really required for your object to be constructed (without them the object cannot start to live). Use properties for the parameters which have an acceptable default value, so it's OK not to assign them at all. You can provide some extra constructors which will assign some properties as a shorthand, courtesy to your users.
You use a constructor when you need arbitrary sane initial values, and properties when you want the values to be changeable later.
There are a few cases where mutable properties may be preferable:
For 'pure' mutable Data objects where merely setting the properties can have no side effects. For instance, you might have an object that represents some Entity in the database, but modifying its properties will not have any effect until you explicitly perform a Commit operation. The object is a package for containing data, but nothing directly reacts to changes in the data.
If you have a large amount of configurable state that will affect some operation and many of the configurable properties have meaningful default values. If these are properties of the class that performs the operation, it's typical to have some notion of 'freezing' the state so that the mutable properties throw exceptions while the operation is running.
If you're developing a class that will be consumed by a visual designer or other system that relies on Reflection over properties. For instance, the data binding system in WPF makes extensive use of mutable properties as a way to communicate UI interactions. With a proper design to manage these mutations, you can create some very powerful and responsive interfaces.
It is possible, given only an interface, to create an object from this?
Something like:
var obj = new IWidget();
(I know this code isn't right - VS stays cannot create an instance of IWidget)
I'm in a context where my project has references to the interfaces, and I want to create concrete objects and return them from a method - but I can't figure out how to create the objects purely from the interfaces.
You can't create an object from an interface. You can create an object from a class that uses that interface.
For example:
IList<string> x = new IList<string>();
will not work.
IList<string> x = new List<string>();
will.
Interfaces cannot be created, only objects that use the interface can be created.
That code is actually correct for COM objects, due to compiler wizardry. Normally it's not though.
The problem is, how is the compiler meant to know which implementation to create? There could be any number around. You might want to consider having a factory for the interface, or possibly using dependency injection (e.g. with Spring.NET or Castle Windsor).
This will not be possible purely from the interfaces (and shouldn't be, what if there is more than one implementation of it?). It sounds like what you want to do is expose an interface, but not the implementation. Is that correct?
You essentially would want a Factory Pattern. This pattern involves making a method that returns the interface, but internally instantiates a concrete type. It lets you hide the concrete type from anyone using the interface.
If you go a step further you could use Inversion of Control (IoC). I don't know what the best option is for doing this in .Net, but one option is Spring.Net. You use a configuration file to define all of the different setups for your concrete objects, and then have spring automatically "inject" those instances into your classes that use the interface.
No would be the short answer. But I guess you could use an IoC container to inject an implemtation.
You might be looking for a Dependency Injection framework.