Creating objects from an interface in C# - c#

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.

Related

Register 2 implementations of the same class

Having 2 classes implementing the same interface, how to register them?
The first registration works well:
iocContainer.Register<IEcContract, EcContract>(Lifestyle.Transient);
But if I register the second class with the same interface, it throws an error. I am using Simple Injector.
What do you expect from the container? Which instance should it return?
If you for some reason need to resolve all the instances (in a collection), see swatsonpicken's answer.
If you need a specific implementation, you need a way to decide which one.
Some DI libraries let you name the instances and then ask the container for one of the named instances. Simple Injector does not support it.
So if you need to switch between implementations with Simple Injector, consider writing a custom factory which always returns the implementation you need.
I don't know this IoC container, but others use a scheme like this:
container.RegisterCollection<IEcContract>(new[] { typeof(EcContract), typeof(OtherClass)});
Maybe check the documentation for your IoC container and see if there's a RegisterCollection (or similar) method.

Which pattern am I looking for?

Say I have the following interface:
ICarProvider
And the following classes implementing it:
RedCarProvider:ICarProvider
BlueCarProvider:ICarProvider
GreenCarProvider:ICarProvider
Now, what I would like to do is this:
Depending on the settings of the user, create a single instance of one (only one) of these classes and use that throughout the entire session of the application. So my logic should only know the interface and where to get the instance.
Is there a pattern for this?
Thanks!
It's called the factory pattern.
Singleton Factory
http://www.wikijava.org/wiki/Singleton_Factory_patterns_example
Singleton Factory method
Creating singleton factory
Abstract Factory pattern. Read more on wikipedia.org
In software development, a factory is the location in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage. This allows for new derived types to be introduced with no change to the code that uses the base class.
That sounds like the some sort of factory pattern.
I can't refrain myself from being sceptical about the need for a pattern to describe something so trivial.
That what you have presented seems to be a factory patter, but you should not create a class only for describing the properties of an object, sometime is better to use an map for those.

In which cases it makes sense to use factory classes instead of static functions?

Currently I have created a ABCFactory class that has a single method creating ABC objects. Now that I think of it, maybe instead of having a factory, I could just make a static method in my ABC Method. What are the pro's and con's on making this change? Will it not lead to the same? I don't foresee having other classes inherit ABC, but one never knows!
Thanks
Having a single, static method makes this much more difficult to test whereas having an instantiable object allows this to be easier to test. Also, dependency injection is later more of an option with the non-static solution.
Of course, if you don't need any of this, then these are not good arguments.
The main advantage of the factory method is the ability to hide reference to a specific class behind an interface. Since static methods can not be a part of the interface, static factory methods are basically the same as the constructor method itself. The only useful application of the static factory methods is to provide access to a private constructor - what is commonly used for singleton-pattern implementation.
In reality, if you want to get the benefits of a factory class, you need the static method in it's own class. This will allow you to later create new factory classes, or reconfigure the existing one to get different behaviors. For example, one factory class might create Unicorns which implement the IFourHoovedAnimal interface. You might have an algorithm written that does things with IFourHoovedAnimal's and needs to instantiate them. Later you can create a new factory class that instead instantiates Pegasus's which also implement IFourHoovedAnimal's. The old algorithm can now be reused for Pegasus's just by using the new factory! To make this work both the PegasusFactory and the UnicornFactory must inherit from some common base class(usually an abstract class).
So you see by placing the static method in it's own factory class, you can swap out factory classes with newer ones to reuse old algorithms. This also works for improving testability, because now unit tests can be fed a factory that creates mock objects.
I have done the latter before (static factory method on the class that you are creating instances of) for very small projects, but it was only because I needed it to help refactor some old code, but keep changes to a minimum. Basically in that case I had factored out a chunk of code that created a bunch of ASP.NET controls, and stuff all those controls into a user control. I wanted to make my new user control property based, but it was easier for the old legacy code to create the user control with a parameter based constructor.
So I created a static factory method that took all the parameters, and then instanced the user control and set it's properties based on the parameters. The old legacy code used this static method to create the user control, and future code would use the "prettier" properties instead.
For concrete classes, factory methods are really just a method of indirection around creating the actual type (which isn't to say they aren't useful, but as you've found, the factory method could really be anywhere).
Where the factory method really shines though is when your method creates instances of an interface type.
The "D" in Uncle Bob's SOLID Principles of Object Oriented Design is "The Dependency Inversion Priciple" Depend on abstractions, not on concretions.
An extreme following of that principle could have your main class create all your factories, with each factory using other factories via interfaces. The only appearance of "new" (creating concrete objects) would be in your main class, and your factories. All your objects would work with interfaces (abstractions), with the concrete dependencies obtained from supplied factory implementations.
You could then very easily adjust, or provide multiple Main classes customised for different scenarios.
Overuse of design patterns are dangerous, and creational design patterns make sense when you have class hierarchies with defined interfaces, or need to build rather complex objects. If you have a simple design, use simple solutions. Therefore, in your case, Factory Method would be enough
Yes, you are right, it is another design pattern :)

Why we are implementing interfaces ?

Why are we implementing, for example ICloneable or IDisposable. I'm not asking what ICloneable or IDisposable do, but I want to learn what's a good reason to implement these interfaces rather than just writing a method which disposes or clones our objects?
Using interfaces keeps the use of those pieces of functionality consistent. That way, when another class wants to / needs to use your class, it can act on it as a cloneable, disposable object without worrying about your particular implementation details.
By implementing a well known interface, you can have polymorphism, which enable you to write generic code that can act on any instance of a class that implementes a given interface.
You can check the Wikipedia article on polymorphism for more.
Because you may want the same code to operate on instances of different classes. For example, a form cleanup routine wants to iterate over all components and dispose them. In order for it to do this, it needs to refer to the components through a type: either a common base class or an interface. Single inheritance means that a common base class isn't always feasible (suppose my form has both a FileStream and a Button -- what common base class could they have that the cleanup routine would access them through?); hence interfaces.
Adding to more interface wisdom, interfaces can be used as contracts between consumer code and service code. Instead of saying this is object that we will be dealing with, with interfaces the agreement is, this is how the object i return looks. In code, it could be something like:
service code
public IEnumerable<int> GetNumbers(){ return new []{1,2,3,4,5}; }
client code :
var result = serviceProxy.GetNumbers();
Here the service code can change implementation to return any class that satisfies IEnumerable without breaking client code.
Besides all this you have got other applications like IoC DI, Unit Testing, Object Mocking. All this reaping benefits of polymorphic goodness.
Among other reasons, read about the using block.
Phoebus gave a great answer, but to add a bit more.
It forces you to write the methods that are expected for cloning or making something that can be disposed. If you had to write just the method, would you always include all the necessary methods, or would the signature always be the same?
If there is a new framework, and they add something, to help ensure that the operations are done correctly, by having interfaces then it forces you to implement any new changes, as your application will no longer compile.
In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently.
Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface.
Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.
An interface separates what's done from how it's done. Clients deal with the interface type, without having to know what the implementation class is, because they can rely on the contract it enforces.
This is important for situations that generate dynamic proxies. Clients need not know that they're dealing with a proxy, which gives you the freedom to inject whatever behavior you need. It's a common technique for aspect-oriented programming.

When to use activator and when to use factory method?

I have learnt the factory method design pattern, and at the same time, I have come across the Activator object and how to use it, from reading a tutorial (I have come across this object in intellisense a lot thougha).
Activator allows late binding, which can be extremely useful. But this is because we don't know what class we want to instantiate. Likewise, the factory method deals with the same problem in software engineering.
At a simple level, a bunch of ifs or a case statement and then instantiating an object based on the if condition is an implementation of the factory method, right?
On on a related topic, I have read that polymorphism can reduce coupling between objects by eliminating case statements. Is there an example of this?
Thanks
If you know at compile time all of the potential classes you would want to instantiate, use the Factory pattern, it will be faster and lets the compiler check your type safety.
On the other hand, if you don't know all of the classes that might need to be instantiated (for example, if you are trying to provide a plugin architecture), your only option is to use Activator.
The simple rule of thumb here is this: Choose a factory over using Activator (or any other type of runtime binding) as long as the scenario allows it.

Categories