Is it possible to use C# Object Initializers with Factories [duplicate] - c#-3.0

This question already has answers here:
Is it possible to use a c# object initializer with a factory method?
(7 answers)
Closed 9 years ago.
I'm looking at the new object initializers in C# 3.0 and would like to use them. However, I can't see how to use them with something like Microsoft Unity. I'm probably missing something but if I want to keep strongly typed property names then I'm not sure I can. e.g. I can do this (pseudo code)
Dictionary<string,object> parms = new Dictionary<string,object>();
parms.Add("Id", "100");
IThing thing = Factory.Create<IThing>(parms)();
and then do something in Create via reflection to initialise the parms... but if I want it strongly typed at the Create level, like the new object intitalisers then I don't see how I can.
Is there a better way?
Thanks

AFAIK, it's not possible to do. I would stay away from reflection in this case if I were you, as reflection is really really slow and could become easily a bottleneck in your application. I think using reflection for this is actually abusing reflection.
Do not shoot yourself in the leg because you want to emulate some syntactic sugar. Just set the fields / properties of the instance one by one, the classic way. It will be much faster than reflection.
Remember: No design pattern is silver bullet. Factory methods and object initializers are nice but try to use common sense and only use them when they actually make sense.

I'm not that familiar with Unity, but the idea behind IoC/DI is that you do not construct object yourself, so of course you can't use object initializer syntax.
I guess what you could use from C# 3.0 in your example is an anonymous type instead of Dictionary. No idea if Unity can consume that.
Anyway, if you make those calls like Factory.Create() you are probably using IoC in a wrong way.

Consider investing the time in leaning Unity or Castle or any of the other IOC frameworks available for .net. The IOC will let you transfer the complexity of object initialization from your code to a configuration file. In your application you will use interfaces to access the objects initialize in by the IOC container. The other service the IOC gives you is control of the lifetime of the objects (singletons, etc).

Graham, the idea behind IoC/DI is that your components declare their dependencies as either constructor parameters or public properties of specific types (usually interfaces).
The container then builds a dependency graph and satisfies those (with regards to component lifestyle if case of mature IoC's like Castle Windsor).
So basically you write your components, state dependencies and then register contracts and implementations in IoC container and don't care about constructing objects anymore. You just make a single call similar to Application.Start() :)
The bad thing is that some frameworks are hard to integrate with. Like ASP.NET WebForms, where you don't have control over IHttpHandler creation and cannot setup factories that would use IoC to instantiate those. You can check Ayende's "Rhino Igloo" which does it's best to use IoC in an environment like this.

Maybe this can help... Have you checked out this blog post?
http://www.cookcomputing.com/blog/archives/000578.html
The author presents a method for building an object from a factory and registering the object in the IoC container.

This is answered better in this question: Is it possible to use a c# object initializer with a factory method?.
There were four possibilities:
Accept a lambda as an argument
Return a builder instead
Use a default constructor, passing in an initialized object
Use an anonymous object

Related

Which is better method to expose an object , by using Provider package or , creating an object

We can expose an object of a class by two methods like:
ClassName obj=Classname(); or obj=Provider.of<ClassName>(context);
is there any difference between them , or is there anyone of them better method.
ClassName obj = Classname();
This is creating a new instance of Classname. In Dart, you can omit the new keyword (since v2.0), older versions and most other languages actually force you to spell it out:
ClassName obj = new Classname();
It will call the constructor of the class and create a new instance. Alternatives would be named constructors that could look like this:
ClassName obj = Classname.fromInt(42);
That said, what exactly is this and what is the difference:
obj = Provider.of(context);
A provider is a form of state management. State management is a complex way of saying "where do I actually call my constructors so that the instances are known to the program at the place and time I need them? Sometimes I want a new instance, sometimes I want the instance I used before."
A provider may create a new instance for you. It may also decide it already has the instance you are looking for. You decide that by configuring it.
The only way to create a new instance of a class is through one of it's constructors. Very likely (but configurable), a provider is using a class constructor to create the instance of a class that it is then providing to multiple layers of your program so you don't have to keep track of that variable yourself.
Keeping track of all your variables and their lifetimes by yourself gets complicated really fast the bigger your program gets.
My personal recommendation to everyone learning programming is: try it the way you already know (in this case: constructors). Then you will experience for yourself what the problem is and you will know why packages like provider or bloc were created. This is a much better learning experience than just believing a random person on the internet (me or someone else) who says they know it's "better". Because then you will understand the problem instead of being railroaded into some cargo cult of "use this, it's good for you".
welcome to the StackOverflow.
You can do both of them, but if you are using the Provider package, you have some benefits:
It is much easier to transfer state to another level (or even really far level) inside your app's tree.
It is really suitable for a large scale app to manage their state (but it's also suitable for the small app).
If you are passing a state or an object directly, you'll be completely in a mess when your app complexity grows (based on my experience).
I hope it will be helpful.
listening is not possible with normal object creation where as with provider it is possible.
obj=Provider.of(context, listen:true);

IoC container that supports constructor injection with Scala named/default arguments?

I would prefer using constructor injection over JavaBean property injection if I could utilize the named and default arguments feature of Scala 2.8. Any IoC-containers exists that supports that or could be easily extended to do so? (The required information is there on runtime in the scala.reflect.ScalaSignature annotation of the class.)
I also have some basic(?) expectations from the IoC container:
Auto-wiring (by target class/trait or annotation, both one-to-one and one-to-many)
Explicit injection (explicit wiring) without much hassle (like Guice is weak there). Like user is injected that way in new ConnectionPool(user="test").
Life-cycle callback for cleanup on shutdown (in the proper order)
Spring can do these, obviosuly, but it doesn't support named parameters. I have considered using FactoryBean-s to bridge Scala and Spring, but that would mean too much hassle (boilerplate or code generation), as far as I see.
PART A
I have a work-in-progress reflection library that parses the Scala signature and is currently able to resolve named parameters: https://github.com/scalaj/scalaj-reflect
Unfortunately, I haven't yet tied it back into Java reflection to be able to invoke methods, nor have I added the logic to resolve default values (though this should be trivial). Both features are very high on my to-do list :)
This isn't an IoC container per-se, but it's a pre-requisite for another project of mine: https://github.com/scalaj/scalaj-spring. Work on scalaj-spring stopped when it became blindingly obvious that I wouldn't be able to make any worthwhile further progress until I had signature-based reflection in place.
PART B
All of that stuff is intended for big enterprisey people anyway. Those with no choice but to integrate their shiny new Scala code into some hulking legacy system... If that's not your use case, then you can just do Scala DI directly inside Scala.
There's DI support provided under the Lift banner: http://www.assembla.com/wiki/show/liftweb/Dependency_Injection
You should also hunt around for references to the cake pattern
Another dependency injection framework in Scala is subcut
I have considered using FactoryBean-s to bridge Scala and Spring, but that would mean too much hassle
I am not sure I understand the complexity. Its actually quite simple to implement Spring FactoryBeans in Scala. Check this little write-up http://olegzk.blogspot.com/2011/07/implementing-springs-factorybean-in.html
I've just released Sindi, an IoC container for the Scala programming language.
http://aloiscochard.github.com/sindi/

Code to interfaces instead of implementations? [duplicate]

This question already has answers here:
Should you always Code To Interfaces In Java [closed]
(6 answers)
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
I believe that it's better to code to interfaces instead of implementations. In Java:
List<User> users = new ArrayList<User>();
There's no need to specify the runtime type of users all over the program if the code only cares that it implements List.
However, I encounter many people who believe that it's totally fine, even when they're not using properties specific to the ArrayList:
ArrayList<User> users = new ArrayList<User>();
I try to explain that it's redundancy and makes the program harder to change, but they don't seem to care. Are there other reasons that this is important? Or perhaps my convictions are overstated?
Personally, I think that there are two parts to this argument.
If you're returning an object from a method in a class, it should return the most generic object possible. In this case, if you had a choice between returning ArrayList<User> or List<User>, return List<User> because it makes life easier for the people consuming your class.
If you're coding inside of a method and you don't mind hard-coding a concrete type, go for it. It's not what I would do, and it will make your code more fragile in the future but since there are no outside dependencies on that concrete type (hence the first part), you're not going to break anybody that is consuming your code.
Testability is one reason. If you implement using implementations it is very difficult to mock out the required object and use it in tests. You usually end up extending the implementation and overriding which is painful.
It is extremely important if you want to use dependency injection. It is also important for hibernate -- you MUST specify an interface if you have a collection type, because hibernate provides its own collection implementations.
That said, you don't need to be pedantic about it -- sometimes it doesn't matter. Sometimes you want to specify concrete type to get at methods only available on that type.

CORBA: Can a CORBA IDL type be an attribute of another?

Before I start using CORBA I want to know something.
It would seem intuitive to me that you could use an IDL type as an attribute of another, which would then expose that attribute's methods to the client application (using ".") as well.
But is this possible?
For example (excuse my bad IDL):
interface Car{
attribute BrakePedal brakePedal;
//...
}
//then.. (place above)
interface BrakePedal{
void press();
//...
}
//...
Then in the client app, you could do: myCar.brakePedal.press();
CORBA would seem crappy if you couldn't do these kind of multi-level
object interfaces. After all, real-world objects are multi-level, right? So can
someone put my mind at ease and confirm (or try, if you already have CORBA set up) if this definitely works? None of the IDL documentation explicitly shows this in example, which is why I'm concerned. Thanks!
Declaring an attribute is logically equivalent to declaring a pair of accessor functions, one to read the value of the attribute, and one to write it (you can also have readonly attributes, in which case you would only get the read function).
It does appear from the CORBA spec. that you could put an interface name as an attribute name. I tried feeding such IDL to omniORB's IDL to C++ translator, and it didn't reject it. So I think it is allowed.
But, I'm really not sure you would want to do this in practice. Most CORBA experts recommend that if you are going to use attributes you only use readonly attributes. And for something like this, I would just declare my own function that returned an interface.
Note that you can't really do the syntax you want in the C++ mapping anyway; e.g.
server->brakePedal()->press(); // major resource leak here
brakePedal() is the attribute accessor function that returns a CORBA object reference. If you immediately call press() on it, you are going to leak the object reference.
To do this without a leak you would have to do something like this:
BrakePedal_var brakePedal(server->brakePedal());
brakePedal->press();
You simply can't obtain the notational convenience you want from attributes in this scenario with the C++ mapping (perhaps you could in the Python mapping). Because of this, and my general dislike for attributes, I'd just use a regular function to return the BrakePedal interface.
You don't understand something important about distributed objects: remote objects (whether implemented with CORBA, RMI, .NET remoting or web services) are not the same as local objects. Calls to CORBA objects are expensive, slow, and may fail due to network problems. The object.attribute.method() syntax would make it hard to see that two different remote calls are being executed on that one line, and make it hard to handle any failures that might occur.

Encapsulation in the age of frameworks

At my old C++ job, we always took great care in encapsulating member variables, and only exposing them as properties when absolutely necessary. We'd have really specific constructors that made sure you fully constructed the object before using it.
These days, with ORM frameworks, dependency-injection, serialization, etc., it seems like you're better off just relying on the default constructor and exposing everything about your class in properties, so that you can inject things, or build and populate objects more dynamically.
In C#, it's been taken one step further with Object initializers, which give you the ability to basically define your own constructor. (I know object initializers are not really custom constructors, but I hope you get my point.)
Are there any general concerns with this direction? It seems like encapsulation is starting to become less important in favor of convenience.
EDIT: I know you can still carefully encapsulate members, but I just feel like when you're trying to crank out some classes, you either have to sit and carefully think about how to encapsulate each member, or just expose it as a property, and worry about how it is initialized later. It just seems like the easiest approach these days is to expose things as properties, and not be so careful. Maybe I'm just flat wrong, but that's just been my experience, espeically with the new C# language features.
I disagree with your conclusion. There are many good ways of encapsulating in c# with all the above mentioned technologies, as to maintain good software coding practices. I would also say that it depends on whose technology demo you're looking at, but in the end it comes down to reducing the state-space of your objects so that you can make sure they hold their invariants at all times.
Take object relational frameworks; most of them allow you to specify how they are going to hydrate the entities; NHibernate for example allows you so say access="property" or access="field.camelcase" and similar. This allows you to encapsulate your properties.
Dependency injection works on the other types you have, mostly those which are not entities, even though you can combine AOP+ORM+IOC in some very nice ways to improve the state of these things. IoC is often used from layers above your domain entities if you're building a data-driven application, which I guess you are, since you're talking about ORMs.
They ("they" being application and domain services and other intrinsic classes to the program) expose their dependencies but in fact can be encapsulated and tested in even better isolation than previously since the paradigms of design-by-contract/design-by-interface which you often use when mocking dependencies in mock-based testing (in conjunction with IoC), will move you towards class-as-component "semantics". I mean: every class, when built using the above, will be better encapsulated.
Updated for urig: This holds true for both exposing concrete dependencies and exposing interfaces. First about interfaces: What I was hinting at above was that services and other applications classes which have dependencies, can with OOP depend on contracts/interfaces rather than specific implementations. In C/C++ and older languages there wasn't the interface and abstract classes can only go so far. Interfaces allow you to tie different runtime instances to the same interface without having to worry about leaking internal state which is what you're trying to get away from when abstracting and encapsulating. With abstract classes you can still provide a class implementation, just that you can't instantiate it, but inheritors still need to know about the invariants in your implementation and that can mess up state.
Secondly, about concrete classes as properties: you have to be wary about what types of types ;) you expose as properties. Say you have a List in your instance; then don't expose IList as the property; this will probably leak and you can't guarantee that consumers of the interface don't add things or remove things which you depend on; instead expose something like IEnumerable and return a copy of the List, or even better, do it as a method:
public IEnumerable MyCollection { get { return _List.Enum(); } } and you can be 100% certain to get both the performance and the encapsulation. Noone can add or remove to that IEnumerable and you still don't have to perform a costly array copy. The corresponding helper method:
static class Ext {
public static IEnumerable<T> Enum<T>(this IEnumerable<T> inner) {
foreach (var item in inner) yield return item;
}
}
So while you can't get 100% encapsulation in say creating overloaded equals operators/method you can get close with your public interfaces.
You can also use the new features of .Net 4.0 built on Spec# to verify the contracts I talked about above.
Serialization will always be there and has been for a long time. Previously, before the internet-area it was used for saving your object graph to disk for later retrieval, now it's used in web services, in copy-semantics and when passing data to e.g. a browser. This doesn't necessarily break encapsulation if you put a few [NonSerialized] attributes or the equivalents on the correct fields.
Object initializers aren't the same as constructors, they are just a way of collapsing a few lines of code. Values/instances in the {} will not be assigned until all of your constructors have run, so in principle it's just the same as not using object initializers.
I guess, what you have to watch out for is deviating from the good principles you've learnt from your previous job and make sure you are keeping your domain objects filled with business logic encapsulated behind good interfaces and ditto for your service-layer.
Private members are still incredibly important. Controlling access to internal object data is always good, and shouldn't be ignored.
Many times private methods I've found to be overkill. Most of the time, if the work you're doing is important enough to break out, you can refactor it in such a way that either a) the private method is trivial, or b) is an integral part of other functions.
In addition, with unit testing, having many methods private makes it very hard to unit test. There are ways around that (making test objects friends, etc), but add difficulties.
I wouldn't discount private methods entirely though. Any time there's important, internal algorithms that really make no sense outside of the class there's no reason to expose those methods.
I think that encapsulation is still important, it helps more in libraries than anything imho. You can create a library that does X, but you don't need everyone to know how X was created. And if you wanted to create it more specifically to obfuscate the way you create X. The way I learned about encapsulation, I remember also that you should always define your variables as private to protect them from a data attack. To protect against a hacker breaking your code and accessing variables that they are not supposed to use.