Could someone please helpme to understand if the following codes are same. If not what's the difference between class and interfance instantiation.
IUnityContainer container = new UnityContainer()
UnityContainer container = new UnityContainer()
As far as I understand Inteface has only method signature and if the interface has been implemented by 3 classes. Not too sure which of the 3 instance would be created by first statement above.
Thankyou.
Interfaces can't be instantiated by definition. You always instantiate a concrete class.
So in both statements your instance is actually of type UnityContainer.
The difference is for the first statement, as far as C# is concerned, your container is something that implements IUnityContainer, which might have an API different from UnityContainer.
Consider:
interface IAnimal
{
void die();
}
class Cat : IAnimal
{
void die() { ... }
void meow() { ... }
}
Now :
IAnimal anAnimal = new Cat();
Cat aCat= new Cat();
C# knows for sure anAnimal.die() works, because die() is defined in IAnimal. But it won't let you do anAnimal.meow() even though it's a Cat, whereas aCat can invoke both methods.
When you use the interface as your type you are, in a way, losing information.
However, if you had another class Dog that also implements IAnimal, your anAnimal could reference a Dog instance as well. That's the power of an interface; you can give them any class that implements it.
There's really no such thing as "interface instantiation", but there are interface variables. The first line is an example of one such variable.
With the first line, you could instantiate container to be any concrete class that implements IUnityContainer. With the second line, the container object could only be instantiated from the UnityContainer class or a derived class.
When you use interface variables in your code, it allows you to more easily switch out the concrete implementation, which makes your code more flexible.
Interface instantiation is not possible. But when we created an an object for interface using its implemented class it works.
IUnityContainer container = new UnityContainer()// It is assigning an object of its implemented class.
UnityContainer container = new UnityContainer() // To access directly by using like this.
Assume that there is a multiple inheritance, to achieve this we need to go with first.
There is no need to provide such things we go with second way.
Interfaces restricts direct access of the data and members of its class.
The object instantiated and stored in the IUnityContainer container variable is considered by the compiler to have only the members defined in the IUnityContainer interface. That is, if the UnityContainer class contains members that aren't defined by the IUnityContainer interface, you won't be able to invoke them. On the other hand, you could "put" any object that implements the IUnityContainer interface in the IUnityContainer container variable--not just instances of UnityContainer. With the second declaration, you're stuck with instances of UnityContainer and objects in its inheritance hierarchy.
Check out the C# Programming Guide to Interfaces for more information on interfaces and how they're used.
Related
If have two classes Class1 and Class2 both implementing an interface IInterface.
And now, if I need a singleton instance of each of these classes, would this be the right way to implement it?
c.ForSingletonOf<IInterface>().Use<Class1>().Named("Class1");
c.ForSingletonOf<IInterface>().Add<Class2>().Named("Class2");
And then getting the instances like this:
container.GetInstance<IInterface>("Class1");
container.GetInstance<IInterface>("Class2");
Is there anything wrong in this approach or is there a better approach?
If you want access to a specific implementation of IInterface you will need access to the container in order to request the specific named instance.
Constructor injection will always provide you with Class1 as that is what you have told structuremap to use for IInterface. So this will probably lead you to pass the container around which is a very bad idea.
If the objects need to be created as singletons, I would suggest not injecting as IInterface but as Class1 and Class2. They are first class citizens in your application and qualify for direct access.
c.ForSingletonOf<Class1>().Use<Class1>();
c.ForSingletonOf<Class2>().Use<Class2>();
Depending on what blogs you read, you may want to specify the implementation of Class1 and Class2 as interfaces attributing to what purpose they provide. This way you future proof them if the backing singleton of IClass1 or IClass2 should change.
public interface IClass1 : IInterface { }
public interface IClass2 : IInterface { }
-----
c.ForSingletonOf<IClass1>().Use<Class1>();
c.ForSingletonOf<IClass2>().Use<Class2>();
That is how I would go about it. Named instances in the container I have found are only useful when configuring the container as I have access to it. When it comes to dependency injection they are not useful as the named instance you require is specified by the class/interface name. If you require more than one implementation of the same interface, they qualify for their own interface imo
I have a generic class, let's call it MyClass<T>, which will need to have a factory method so to abstract constructor details away from client code.
Which of the two options is correct? (example instantiation code included)
Static non-generic factory method on the original generic MyClass<T>:
MyClass<SomeType> instance = MyClass<SomeType>.CreateNew();
Static generic factory method on a dedicated, non-generic static MyClass implementation:
MyClass<SomeType> instance = MyClass.CreateNew<SomeType>();
On the first sight, looks like proper answer to your question is #1. This is because your class is MyClass<T> and hence factory should also be T-specific. But there is more into it than this simple answer.
Before proceeding, I would add the third possibility: non-static factory class. Object which relies on a factory would have a public property through which it receives a factory object. Getter of the property would instantiate default factory if no other instance has been assigned. This allows dependency injection later, and also helps write unit tests that rely on their own fake factory. Solution would look something like this (ignore generics for a moment):
public class ISomeFactory { ... }
public class DefaultSomeFactory: ISomeFactory { ... }
public class ClientClass
{
public ISomeFactory FactoryOfSome // Right place for dependency injection
{
get
{
if (_fact == null)
_fact = new DefaultFactory();
return _fact;
}
set { _fact = value; }
}
private ISomeFactory _fact;
}
Now as I said, your class goes with generic parameter MyClass<T> and then factory should go with generic parameter as well: Factory<T>. This solution is better than generic method on general factory, simply because creating an instance may be T-specific. Solution with generic factory allows you this:
public class SpecialSomeFactory: DefaultSomeFactory<string> { ... }
In this way, you can override behavior of existing factory class and have an alternative way to generate instances that are specialized for strings. This is important because dealing with strings is often much different than dealing with primitive types like int or double. Having an opportunity to specialize the factory may be beneficial. But now you see why it might be a bad idea to have a static factory - statics cannot be extended.
Both examples are essentially variations on the service locator pattern. Controversially, this is often considered an anti-pattern as the dependencies of a class that uses it are not visible to its consumers.
A way to make your dependencies more explicit would be to adopt a solution similar to the first example, but make CreateNew() an instance method, as opposed to a static one.
BaseClass obj = new SubClass(); // Subclass : BaseClass
What does that mean in OOP? When would I want to do that instead of just creating a SubClass object? If someone can give me a real life example I would really apreciate it.
obs: I understand there's some side effects regarding virtual methods and stuff, but what I'm really confused here is about the concept and uses of this.
The most common reason that I can think of would be in a scope where multiple types of subclass may be assigned to that variable:
Vehicle myWheels;
if (iHaveALicense) {
myWheels = new Car();
} else {
myWheels = new Bus();
}
A very simple example is to think about a factory class. If one class takes a dependency on some Factory<T>, you can inject the "concrete" version, using inheritance. The consuming class doesn't care about how the concrete version works, just that it implements some contract.
"What does that mean in OOP?" - In C#, it means that SubClass inherits everything about BaseClass and has access to everything inside of BaseClass, minus private members. By doing this, anywhere a BaseClass is required, a SubClass may be used in its place. In my example, you might define what a factory should do by exposing an abstract base class. The inheriting class is then free to implement the behavior without any consumers caring about how the work is being done.
(This is only one example--inheritance, when not abused, is a very powerful tool.)
Assume you have another class which inherits BaseClass:
public class NewSubClass : BaseClass
When you initialize your object the way you shown, you can do that:
BaseClass obj = new SubClass();
obj = new NewSubClass();
on the other hand something like that:
SubClass obj = new SubClass();
obj = new NewSubClass();
wouldn't compile at all.
That would be called polymorphism.
suppose there is a function that takes baseclass as argument.
void my_function(Animal ani)
{
Console.WriteLine(ani.makeSound());
}
Now if you make virtual method in the base class and override them in the derived class and then pass any object derived from animal to the function. Then makeSound would make generate sound according to the derived object that you have passed.
That way you don't have to make this function for everytype of animal that produces sound.
Lets say we have a namespace called AllFoos.
And Lets say all classes in the AllFoos namespace implement a specific interface called IFoo and are all singletons.
Now we have:
HashSet<IFoo> myFoos = new HashSet<IFoo>();
What would be the code to populate the collection MyFoos with the singleton instances of all the classes in AllFoos?
The singleton implementation for all of these classes is:
private static IFoo _instance = new ConcreteImplementationOfFoo1();
public static IFoo Instance
{
get
{
return _instance;
}
}
If you would use a dependency injection framework you could:
register your classes as "singleton" in the container
register all implementations easily (good frameworks allow mass-registration based on some patterns)
resolve all implementations of your interface as a list
If you want to go the classic way, you have to tell how your singleton pattern looks like (e.g. static Instance property?), and it can be solved with classic reflection as mentioned in the comments already.
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.
But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?
A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.
IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.
//Register instance at some starting point in your application
container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());
//This single instance can then be resolved by clients directly, but usually it
//will be automatically resolved as a dependency when you resolve other types.
IActiveSessionService session = container.Resolve<IActiveSessionService>();
You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.
You can't do this with interfaces since they only specify instance methods but you can put this in a base class.
A singleton base class:
public abstract class Singleton<ClassType> where ClassType : new()
{
static Singleton()
{
}
private static readonly ClassType instance = new ClassType();
public static ClassType Instance
{
get
{
return instance;
}
}
}
A child singleton:
class Example : Singleton<Example>
{
public int ExampleProperty { get; set; }
}
A caller:
public void LameExampleMethod()
{
Example.Instance.ExampleProperty++;
}
You can make all the other members of your singleton implement corresponding members in an interface. However, you are correct that the Instance property cannot be part of the interface since it is (and must remain) static.
Interfaces can not have instances in C#, I think you only need to:
Implement the singleton pattern (yes, you'll need a static attribute or method to get the instance, but everything else does not require to be static)
On the other hand, your singleton can implement an interface if you want, just remember that other classes can also implement that same interface